1、項目根目錄下新建文件夾:custom-tab-bar (文件夾名字必須是custom-tab-bar)
在custom-tab-bar下新建一個名為index的component組件進行自定義tabbar開發。
2、使用van-weapp-ui的tabbar組件自定義tabbar
組件中先引入vant-weapp的tabbar組件。
custom-tab-bar/index.json:
{
"component": true,
"usingComponents": {
"van-tabbar": "@vant/weapp/tabbar/index",
"van-tabbar-item": "@vant/weapp/tabbar-item/index"
}
自定義tabbar組件:
custom-tab-bar/index.wxml:
<!--components/tabbar/tabbar.wxml-->
<view>
<van-tabbar active="{{ active }}" bind:change="onChange">
<van-tabbar-item>
<image slot="icon" src="../images/bar11.png" mode="aspectFit" style="width: 24px; height: 24px;" />
<image slot="icon-active" src="../images/bar12.png" mode="aspectFit" style="width: 24px; height: 24px;" /> 首頁</van-tabbar-item>
<van-tabbar-item >
<image slot="icon" src="../images/bar21.png" mode="aspectFit" style="width: 24px; height: 24px;" />
<image slot="icon-active" src="../images/bar22.png" mode="aspectFit" style="width: 24px; height: 24px;" /> 訂單</van-tabbar-item>
<van-tabbar-item>
<image slot="icon" src="../images/bar31.png" mode="aspectFit" style="width: 24px; height: 24px;" />
<image slot="icon-active" src="../images/bar32.png" mode="aspectFit" style="width: 24px; height: 24px;" /> 我的</van-tabbar-item>
</van-tabbar>
</view>
custom-tab-bar/index.js:
// components/tabbar/tabbar.js
const app = getApp()
Component({
/**
* 組件的屬性列表
*/
properties: {
},
/**
* 組件的初始數據
*/
data: {
active:0,
isShow:false,
list: [//在這里申明tabbar的路徑
{
text: '首頁',
url: '/pages/home/home'
},
{
text: '訂單',
url: '/pages/order/order'
},
{
text: '我的',
url: '/pages/my/my'
}
],
infoNum:'',
},
/**
* 組件的方法列表
*/
methods: {
onChange(event) { //點擊跳轉tabbr頁面的事件
this.setData({ active: event.detail });
wx.switchTab({
url: this.data.list[event.detail].url
});
},
init() { // 初始化
//需要在每個tabbar的js文件的onShow函數中調用這個方法。
//調用方式 this.getTabBar().init();
const page = getCurrentPages().pop();
this.setData({
active: this.data.list.findIndex(item => item.url === `/${page.route}`)
});
}
}
})
在app.json中定義tabbar
{
"tabBar": { //這部分來定義tabbar的頁面路徑等
"custom": true,
"color": "#000000",
"selectedColor": "#000000",
"backgroundColor": "#000000",
"list": [
{
"pagePath": "pages/home/home"
},
{
"pagePath": "pages/order/order"
},
{
"pagePath": "pages/my/my"
}
]
},
"pages": [
"pages/login/login",
"pages/logs/logs",
"pages/home/home",
"pages/order/order",
"pages/my/my"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "商城",
"navigationBarTextStyle": "black"
},
"style": "v2",
"sitemapLocation": "sitemap.json"
}
此時點擊tabbar時會出現錯亂的情況。需要在每個tabbar的js文件的onShow鈎子函數中去調用custom-tab-bar/index.js的init方法:
// pages/home/home.js
Page({
/**
* 頁面的初始數據
*/
data: {
},
/**
* 生命周期函數--監聽頁面顯示
*/
onShow: function () {
this.getTabBar().init();
},
})