微信小程序开放文档中关于Tabbar的踩坑
本文最后更新于:2 小时前
序
最近被迫充当前端写小程序,用的是原生微信小程序 + Vant UI组件库,在第一步创建 TabBar 的时候就踩坑了,吐槽一下,微信小程序的官方文档对开发者真的及其不友好。下面来看一下在 TabBar 里踩的坑吧。
微信官方文档是这么说的
总结一下,一共分为以下几个步骤
在 app.json 中的 tabbar ,把
custom
字段设置为 true ,然后在 list 中设置路径和标题在根目录下创建自定义 tabBar 组件的四个文件
在 custom-tab-bar/index.js 中, list里存放进和在 app.json 中的 list 相同的页面
在 list 的定义的每个页面中,在其 页面.js 里面的添加如下函数即可
onShow: function() { this.getTabBar.init(); }
听起来非常美好,但按照官方文档这样做以后,会出现很多问题…
问题背景
按照官方文档的教程,我首先创建了两个 Tabbar 页面,分别是 首页
和 我的
代码如下
app.json
"tabBar": {
"custom": true,
"color": "#000000",
"selectedColor": "#000000",
"backgroundColor": "#000000",
"list": [{
"pagePath": "pages/index/index",
"text": "首页"
}, {
"pagePath": "pages/my/index",
"text": "我的"
}]
}
custom-tab-bar/index.js
Component({
data: {
active: 0,
list: [{
icon: 'home-o',
text: '首页',
url: '/pages/index/index'
},
{
icon: 'contact',
text: '我的',
url: '/pages/my/index'
}
]
},
methods: {
onChange(event) {
this.setData({
active: event.detail
});
wx.switchTab({
url: this.data.list[event.detail].url
});
},
init() {
const page = getCurrentPages().pop();
this.setData({
active: this.data.list.findIndex(item => item.url === `/${page.route}`)
});
}
}
});
custom-tab-bar/index.json
{
"component": true,
"usingComponents": {
"van-tabbar": "@vant/weapp/tabbar/index",
"van-tabbar-item": "@vant/weapp/tabbar-item/index"
}
}
custom-tab-bar/index.wxml
<van-tabbar active="{{ active }}" active-color="#09bb07" inactive-color="#888888" bind:change="onChange">
<van-tabbar-item wx:for="{{ list }}" wx:key="index" icon="{{ item.icon }}">{{ item.text }}
</van-tabbar-item>
</van-tabbar>
按照这样的操作,让微信开发者工具编译一下,看下效果
不错,至少下面的 tabbar 出来了
问题1
然而,在 console 中却出现了报错
问题2
并且,点击 tabbar 中的 我的 以后,虽然页面切换到了 pages/my/index ,底下的 tabbar 的 active 状态只是非常短暂地切换到了 我的 ,然后 active 又切换回了 我的 。。。
也就是说,绑定的 active
回出错,才会导致 tabbar 的激活状态和页面出现不一致的问题
解决问题
结合官方文档和问题1来看,console 的报错信息指向了在 page.js 中的 this.getTabBar.init()
出错
此时我们下载官方的示例代码来看
。。爷直接无语
结合代码,我们只需要将 page.js 中的代码修改一下就可以了
page.js
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
active: 0
})
}
这里面的 active 值因为小程序的tabbar中并不会太多,我们可以直接手动设置,从0开始按照顺序设置就好了
比如上面的代码是 首页页面,下面的代码是 我的 页面
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
active: 1
})
}
不要再使用 this.getTabBar.init()
了…
按照这样修改后,回到预览,可以看到没问题了
如果实在不放心,可以添加一个点击事件,打印一下当前点击的 index 来验证,这里不再演示了。
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!