小程序动态切换自定义tabbar方案
需求的场景描述:
我现在要根据登录者的权限,动态的去显示或者隐藏某个tabBar,怎么弄??小程序原生tabbar是暂不支持此功能的,tabbar相关api请参考:https://developers.weixin.qq.com/miniprogram/dev/api/ui/tab-bar/wx.showTabBarRedDot.html
方案1:自定义组件 <template is="tabBar" data="{{tabBar:tabBar}}"></template>
- https://www.jianshu.com/p/55d54564ec95
- https://blog.csdn.net/qq_42129925/article/details/89923212
实际应用中:性能相比原生的有点差距,而且有些手机有时候会闪白
方案2:自定义tabbar
-
// app.json
"tabBar": {
"custom": true,//自定义tabbar
"list": [
//所有tabbar页面声明
]
}, -
app.js
//声明全局变量
globalData: {
list: []
},
onLaunch() {
//登录code,获取用户openid以及拿取后台的用户信息
//控制tabbar,修改变量为所展示tabbar
if(xx==’’){
//第一种tabbar
this.globalData.list = [
{
pagePath: "/pages/xx/xx",
iconPath: "/image/xx.png",
selectedIconPath: "/image/xx.png",
text: "首页"
},
{
pagePath: "/pages/xx/xx",
iconPath: "/image/xx.png",
selectedIconPath: "/image/xx.png",
text: "管理"
},
{
pagePath: "/pages/xx/xx",
iconPath: "/image/xx.png",
selectedIconPath: "/image/xx.png",
text: "我的"
}
]
} else {
//第二种tabbar
this.globalData.list = [
{
pagePath: "/pages/xx/xx",
iconPath: "/image/xx.png",
selectedIconPath: "/image/xx.png",
text: "首 页"
},
{
pagePath: "/pages/xx/xx",
iconPath: "/image/xx.png",
selectedIconPath: "/image/xx.png",
text: "我 的"
}
]
}
} -
修改custom-tab-bar/index.js
const app =getApp();
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#1296db",
list: []
},
// 生命周期
attached() {
console.log(app.globalData.list)
this.setData({
list:app.globalData.list
})
},
methods: {
//切换tabbar
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
this.setData({
selected: data.index
})
}
}
}) -
如果选中状态有问题,则可以在对应tabbart页面index.js中修改
onShow: function() {
//添加选中效果
if (typeof this.getTabBar === ‘function’ && this.getTabBar()) {
//自定义组件的getTabBar 方法,可获取当前页面下的自定义 tabBar 组件实例。
this.getTabBar().setData({
selected: 0 //这个是tabBar中当前页对应的下标
})
}
},
浙公网安备 33010602011771号