344 字
2 分钟
微信小程序自定义tabBar
参考文档
::: tip
官网介绍
:::
存在的问题
切换时tabBar闪烁,经过测试发现每个页面所使用的tabBar是独立实例,要避免闪烁需要修改示例代码,原始示例代码如下
官网提供的示例代码-摘录
::: tip 完整版:在开发者工具中预览效果 :::
custom-tab-bar/index.js
Component({ data: { selected: 0, color: "#7A7E83", selectedColor: "#3cc51f", list: [{ pagePath: "/index/index", iconPath: "/image/icon_component.png", selectedIconPath: "/image/icon_component_HL.png", text: "组件" }, { pagePath: "/index/index2", iconPath: "/image/icon_API.png", selectedIconPath: "/image/icon_API_HL.png", text: "接口" }] }, attached() { }, methods: { switchTab(e) { const data = e.currentTarget.dataset const url = data.path this.setData({ selected: data.index }) } }})index/index.js
Component({ pageLifetimes: { show() { if (typeof this.getTabBar === 'function' && this.getTabBar()) { this.getTabBar().setData({ selected: 0 }) } } }})优化方案
既然每个页面都是tabBar独立实例,那么就不需要重复去修改selected这个变量,修改这个变量会触发重新渲染tabBar,也是造成闪烁的原因,修改方案
- 在
custom-tab-bar/index.js的switchTab方法中移除以下代码
this.setData({ selected: data.index})- 在
index/index.js中改为以下代码
Component({ pageLifetimes: { show() { if (typeof this.getTabBar === 'function' && this.getTabBar()) { this.getTabBar().setData({ selected: 0 }) } } },});实际就是让selected这个变量在tabBar中只设置一次,这样可以做只有第一次点击某个tabBar图标时闪烁一次,再次切换不再闪烁,当然如果想要一次闪烁都没有的情况下自定义tabBar那只能使用单页了。
微信小程序自定义tabBar
https://fuwari.vercel.app/posts/微信小程序自定义-tabbar/