启用自定义TabBar
在app.json
中配置"custom": true
,同时将所有可能用到的页面路径预先声明:
1 2 3 4 5 6 7 8 9 10 | { "tabBar" : { "custom" : true , "list" : [ { "pagePath" : "pages/user/home" }, { "pagePath" : "pages/admin/dashboard" }, // 其他所有角色可能用到的页面路径 ] } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // custom-tab-bar/index.js Component({ data: { roleTabs: { user: [ {pagePath: "/pages/user/home" , text: "首页" }, {pagePath: "/pages/user/profile" , text: "我的" } ], admin: [ {pagePath: "/pages/admin/dashboard" , text: "控制台" }, {pagePath: "/pages/admin/analytics" , text: "数据统计" } ] }, currentRole: 'user' // 初始默认角色 }, lifetimes: { attached() { const role = wx.getStorageSync( 'userRole' ) || 'user' this .setData({ currentRole: role }) } } }) |
1 2 3 4 5 6 7 8 9 | methods: { switchRole(roleType) { this .setData({ currentRole: roleType }) wx.setStorageSync( 'userRole' , roleType) // 跳转到该角色的默认首页 const defaultPath = this .data.roleTabs[roleType][0].pagePath wx.switchTab({ url: defaultPath }) } } |
在每个Tab页面的onShow
生命周期同步选中状态:
1 2 3 4 5 6 7 8 9 10 | // pages/user/home.js Page({ onShow() { if ( this .getTabBar?.()) { this .getTabBar().setData({ selectedIdx: 0 // 当前页面在tab数组中的索引 }) } } }) |
通过横向滚动实现超量Tab展示:
1 2 3 4 5 6 | <!-- custom-tab-bar/index.wxml --> <scroll-view scroll-x class= "tab-container" > <view wx: for = "{{roleTabs[currentRole]}}" = "" class= "tab-item {{selectedIdx === index ? 'active' : ''}}" bindtap= "switchTab" data-path= "{{item.pagePath}}" = "" > {{item.text}} </view ></scroll-view scroll-x class= "tab-container" > |
1 2 3 4 5 6 7 8 | // utils/auth.js export function checkTabPermission(role) { const permissions = { user: [ 'home' , 'profile' ], admin: [ 'dashboard' , 'analytics' , 'settings' ] } return permissions[role] || [] } |