mpvue对于custom-tab-bar的支持没在文档上体现,现在此记录一下关于自定义tabBar的用法和注意事项
1、引入custom-tab-bar,直接在src目录下新建custom-tab-bar编译后是不会在dist里面生成custom-tab-bar相关文件,需要把调试好的custom-tab-bar文件夹放到编译出的dist文件夹中,之后调试一律在dist的custom-tab-bar中
2、关于app.json。
app.json的custom字段值应为true,并且需要写usingComponents字段其值默认为{},需要引用第三方插件的时候填写具体值。
详情可见官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/custom-tabbar.html
3、关于tab切换,数据不同步的问题。因为tab打开页面时候,每次打开新的页面就会进入一次tab组件的初始化,此时需要同步数据,使用全局变量来记录之前页面选中的数据,并且每次进入初始化时候需要默认选中tab栏的具体项,使用
this.getTabBar()获取到当前实例再改变数据,这点官方文档也写得很清楚。
以下我custom-tab-bar下index.js的代码,仅供参考。
以上就是我在做custom-tab-bar的总结,虽然都在官网大都是有说明当时写的时候还是要尽量注意一下
Component({
data: {
selected: 0,
color: '#7A7E83',
selectedColor: '#3cc51f',
list: [{
pagePath: '/pages/index/main',
iconPath: 'image/icon_component.png',
selectedIconPath: 'image/icon_component_HL.png',
text: '组件'
}, {
pagePath: '/pages/logs/main',
iconPath: 'image/icon_API.png',
selectedIconPath: 'image/icon_API_HL.png',
text: '接口'
}]
},
lifetimes: {
ready: function () {
if (typeof getApp().globalData.selected === 'number') {
this.getTabBar().setData({
selected: getApp().globalData.selected
})
}
}
},
methods: {
switchTab (e) {
const data = e.currentTarget.dataset
const url = data.path
getApp().globalData.selected = data.index
wx.switchTab({url})
}
}
})