1.首先在小程序根目录miniprogram文件夹下创建 custom-tab-bar 文件夹 包含 index.js index.json index.wxml
其中index.js文件内容 注意url中前面一定要以/开始
// index.js文件
Component({
data: {
active: 0,
list: [
{
"url": "/pages/index/index",
"icon": "home-o",
"text": "主页"
},
{
"url": "/pages/publish/publish",
"icon": "add",
"text": "发布"
},
{
"url": "/pages/my/my",
"icon": "friends-o",
"text": "我的"
}
]
},
methods: {
onChange(e) {
console.log(e,'e')
wx.switchTab({
url: this.data.list[e.detail].url
});
this.setData({ active: e.detail });
},
init() {
const page = getCurrentPages().pop();
this.setData({
active: this.data.list.findIndex(item => item.url === `/${page.route}`)
});
}
}
});
index.json文件内容,以下是通过npm安装的vant webapp
{
"component": true,
"usingComponents": {
"van-icon": "@vant/weapp/icon/index",
"van-tabbar": "@vant/weapp/tabbar/index",
"van-tabbar-item": "@vant/weapp/tabbar-item/index"
}
}
index.wxml文件内容
<!--miniprogram/custom-tab-bar/index.wxml-->
<van-tabbar active="{{ active }}" bind:change="onChange">
<van-tabbar-item wx:for="{{ list }}" wx:key="index" icon="{{ item.icon }}">{{
item.text
}}</van-tabbar-item>
</van-tabbar>
2.修改app.json
app.json文件 把custom置true
全部内容如下:注意pages和tabBar要和如下一样
{
"pages": [
"pages/index/index",
"pages/publish/publish",
"pages/my/my",
"custom-tab-bar/index"
],
"window": {
"backgroundColor": "#F6F6F6",
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#F6F6F6",
"navigationBarTitleText": "云开发 QuickStart",
"navigationBarTextStyle": "black",
"navigationStyle": "custom",
"enablePullDownRefresh": true
},
"sitemapLocation": "sitemap.json",
"style": "v2",
"usingComponents": {
"cu-custom": "/colorui/components/cu-custom"
},
"tabBar": {
"custom": true,
"list": [
{
"text": "首页",
"pagePath": "pages/index/index"
},
{
"text": "发布",
"pagePath": "pages/publish/publish"
},
{
"text": "我的",
"pagePath": "pages/my/my"
}
]
}
}
3.最后每个使用tabbar的页面加上这一句。
/**
* 生命周期函数--监听页面显示 在每个tabbar页面onshow 调用即可;
*/
onShow: function () {
this.getTabBar().init();
},
效果: