需求的場景描述:
我現在要根據登錄者的權限,動態的去顯示或者隱藏某個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中當前頁對應的下標 }) } },