微信小程序基于vant的自定义底部导航栏
基于vant-weapp的底部導(dǎo)航欄,首先根據(jù)vant官網(wǎng)安裝vant
https://vant-ui.github.io/vant-weapp/#/quickstart
由于vant的Tabbar 標(biāo)簽欄自帶翻頁效果,而且不夠美觀,且小程序最多只支持10個頁面棧,點(diǎn)擊多了會導(dǎo)致報錯
報錯如下?
將wx.navigateTo改為wx.redirectTo在反復(fù)多點(diǎn)很多次之后依然會報錯,所以還得優(yōu)化
源碼文件鏈接:
https://download.csdn.net/download/qq_48702470/86838097
貼上代碼:
wxml:
<van-tabbar active="{{ active }}" bind:change="onChange" placeholder><van-tabbar-item wx:for="{{ navList }}" wx:key="index" icon="{{ item.icon }}">{{item.text}}</van-tabbar-item> </van-tabbar>?js:
Component({properties: {navList: {type: Array,default: () => {return [{icon: 'home-o',text: '頁面1',url: '/pages/home/home'},{icon: 'search',text: '頁面2',url: '/pages/mine/mine'}]}},},data: {active: 0},methods: {onChange(event) {// 當(dāng)反復(fù)點(diǎn)擊當(dāng)前的頁面,就不做切換操作了if (event.detail !== this.data.active) {this.setData({active: event.detail});wx.switchTab({url: this.data.navList[event.detail].url});}this.triggerEvent('onFooterNavChange', event)},init() {const page = getCurrentPages().pop();this.setData({active: this.data.navList.findIndex(item => item.url === `/${page.route}`)});}} });json:
{"component": true,"usingComponents": {"van-tabbar": "@vant/weapp/tabbar/index","van-tabbar-item": "@vant/weapp/tabbar-item/index"} }使用方法:
1. 現(xiàn)將組件放入項(xiàng)目根目錄的components文件夾下,自定義組件統(tǒng)一放在這里。(可以不用像微信官方案例一樣的custom-tab-bar直接放在根目錄下,強(qiáng)迫癥表示很難受)
2. 然后在app.json中全局設(shè)置tabBar的custom屬性為true,和其他相關(guān)屬性
微信官方案例:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/custom-tabbar.html
"tabBar": {"custom": true,"color": "#000000","selectedColor": "#000000","backgroundColor": "#000000","list": [{"pagePath": "pages/home/home"},{"pagePath": "pages/mine/mine"}]}3. 開始使用
在需要使用到該組件的頁面wxml中:
<!-- 底部導(dǎo)航欄 --> <footer-nav-barid="footer-nav-bar-id"navList="{{footerNavList}}"bind:onFooterNavChange="onFooterNavChange" > </footer-nav-bar>在需要使用到該組件的頁面js中:
data: {footerNavList: [{icon: 'home-o',text: '首頁',url: '/pages/home/home'},{icon: 'friends-o',text: '我的',url: '/pages/mine/mine'}], },/*** 生命周期函數(shù)--監(jiān)聽頁面顯示*/ onShow() {// 通過id獲取底部導(dǎo)航欄組件,調(diào)用其中的init方法獲取當(dāng)前頁面let footerNavComp = this.selectComponent('#footer-nav-bar-id');// 調(diào)用組件中的init方法,重要,若沒有這一步,在切換導(dǎo)航頁面的時候,底部圖標(biāo)高亮?xí)袉栴}footerNavComp.init() },onFooterNavChange(event) {// 點(diǎn)擊底部導(dǎo)航欄切換后回調(diào)// console.log('點(diǎn)擊底部導(dǎo)航欄', event.detail.detail); }最終實(shí)現(xiàn)效果:
總結(jié)
以上是生活随笔為你收集整理的微信小程序基于vant的自定义底部导航栏的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 非对齐内存访问
- 下一篇: 微信小程序获取手机号 教程(不是完整的)