微信小程序实现自定义tabbar,并解决图标闪烁问题
提示:微信小程序允许开发者根据项目UI需要自定义tabbar,实现个性化,官方文档 戳这里!
demo下载地址: https://developers.weixin.qq.com/s/jiSARvmF7i55
使用步骤
一、配置信息
- 在
app.json
中的tabBar
项指定custom
字段,同时其余tabBar
相关配置也补充完整; - 所有 tab 页的 json 里需声明
usingComponents
项,也可以在app.json
全局开启。
{ "tabBar": { "custom": true, "color": "#000000", "selectedColor": "#000000", "backgroundColor": "#000000", "list": [ { "pagePath": "page/component/index", "text": "组件" }, { "pagePath": "page/API/index", "text": "接口" } ] }, "usingComponents": {} }
二、创建 tabbar 文件
1. 在代码根目录下创建 custom-tab-bar 文件!!!
custom-tab-bar/index.js
custom-tab-bar/index.json
custom-tab-bar/index.wxml
custom-tab-bar/index.wxss
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
this.setData({
selected: data.index
})
}
三、在 tabbar 页面
引用官网:自定义组件新增 getTabBar 接口,可获取当前页面下的自定义 tabBar 组件实例。
每个tab页内容在onShow的时候都需要通过getTabBar
接口设置自定义tabbar里的selected
值;
onShow() {
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
selected: 0
})
}
}
注意:按理说到此,小程序自定的tabbar已经完成了,页面tabbar切换也实现了,但是在真机体验中会出现一个小的图标闪烁问题;
经过一直不妥协的查找,终于给找到了,一个小伙伴提供的在 custom-tab-bar/index.js 中将去掉一段 setdata
switchTab(e) {
const dataset = e.currentTarget.dataset;
const url = dataset.path;
const index = dataset.index;
wx.switchTab({ url})
// this.setData({ selected: index }) //因为我们在tabbat页面已经通过getTabBar设置了selected, 此处就不需要再重复设置了!!!
}
总结
小程序开发还在不断的更新阶段,有一些难免的小bug需要我们不断的去探索,实践,大家一起愉快的ban砖吧!!!