开发时选择vant Weapp作为UI库,其中使用了vant的tabbar来代替小程序原有的tabbar。
本来想用vant tabbar和小程序的自定义tabbar结合来做,具体可以参考:
小程序自定义tabbar
但是在实际使用中,在引用tabbar组件的页面,this.getTabBar总是取不到值,一直null,大概是因为组件中的list和app.json的list页面不一致,我的组件List路径多一个"/",可是改成一模一样的路径,跳转时就会出错。
onShow: function () {
console.log(this.getTabBar())
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 0,
})
}
},
算了算了,就不用小程序自带的自定义tabbar,直接写一个新的,反而更方便,利用组件的properties来设置tabbar的selected。
// tabbar.wxml
<van-tabbar active="{{ selected }}" bind:change="onChange">
<van-tabbar-item wx:for="{{list}}" wx:key="index" icon="{{item.icon}}" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab" class="">
{{item.text}}
</van-tabbar-item>
</van-tabbar>
// tabbar.js
Component({
properties: {
selected: Number
},
data: {
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [{
pagePath: "/pages/todos/todos",
icon: "notes-o",
text: "todo"
}, {
pagePath: "/pages/bookView/bookView",
icon: "description",
text: "book"
}]
},
attached() {},
methods: {
onLoad: function () {
this.data.selected = 0
},
switchTab(e) {
const data = e.currentTarget.dataset
this.setData({
selected: data.index
})
const url = data.path
wx.navigateTo({ url});
}
}
})
// 在页面中引用
// page.js
{
"usingComponents": {
"tab-bar": "../../components/custom-tab-bar/index"
}
}
// page.wxml
<tab-bar selected="1" />
直接写死了selected,很方便,自己用用足够。当然也可以根据当前页面来判断selected的值,这个需要自己加一些代码。