/** * TabBar 配置管理 * 根据用户角色动态显示不同的 tabbar * * 使用说明: * 1. 在 tabBarConfig 中配置所有 tabbar 项 * 2. 通过 roles 数组配置哪些角色可以看到该 tabbar * - roles: [] 或 roles: undefined 表示所有角色都可以看到 * - roles: ['user', 'admin'] 表示只有 user 和 admin 角色可以看到 * 3. 用户角色通过 getUserRole() 函数获取 * - 默认从 uni.getStorageSync('userInfo').role 获取 * - 也可以从 uni.getStorageSync('userRole') 或 uni.getStorageSync('role') 获取 * - 如果都没有,默认返回 'user' * 4. 修改用户角色后,需要重新调用 getVisibleTabBar() 来刷新 tabbar */ // 所有可用的 tabbar 配置 export const tabBarConfig = [ { pagePath: 'pages/index/index', iconPath: '/static/image/home1.png', selectedIconPath: '/static/image/home.png', text: '首页', roles: [] // 空数组表示所有角色都可以看到 }, { pagePath: 'pages/index/publish', iconPath: '/static/image/publish1.png', selectedIconPath: '/static/image/publish.png', text: '发布', roles: ['2'] // 只有 user 和 admin 角色可以看到,可以根据实际需求修改 }, { pagePath: 'pages/index/mine', iconPath: '/static/image/mine1.png', selectedIconPath: '/static/image/mine.png', text: '我的', roles: [] // 所有角色都可以看到 } ] /** * 根据用户角色获取可见的 tabbar 列表 * @param {string} userRole - 用户角色,如 'user', 'admin', 'guest' 等 * @returns {Array} 过滤后的 tabbar 列表 */ export function getVisibleTabBar(userRole = '2') { return tabBarConfig.filter(item => { // 如果没有配置 roles 或 roles 为空数组,表示所有角色都可以看到 if (!item.roles || item.roles.length === 0) { return true } // 检查用户角色是否在允许的角色列表中 return item.roles.includes(userRole) }) } /** * 获取当前用户角色 * @returns {string} 用户角色 */ export function getUserRole() { try { // 方式1: 从存储中获取 const userInfo = uni.getStorageSync('userInfo') if (userInfo && userInfo.role) { return userInfo.role } // 方式2: 从其他存储字段获取(根据实际项目调整) // 可能存储在 userRole、user_role、role 等字段 const role = uni.getStorageSync('userRole') || uni.getStorageSync('role') role = String(role) console.log(role) if (role) { return role } // 方式3: 从 token 或其他地方获取 // const token = uni.getStorageSync('token') // 可以解析 token 获取角色信息 // 默认返回 'user'(可以根据实际需求调整默认角色) return '2' } catch (e) { return '2' } } /** * 获取当前 tabbar 的索引 * @param {string} currentPath - 当前页面路径 * @returns {number} tabbar 索引,-1 表示不在 tabbar 中 */ export function getCurrentTabIndex(currentPath) { const userRole = getUserRole() const visibleTabs = getVisibleTabBar(userRole) // 移除路径前缀的 / 进行匹配 const path = currentPath.startsWith('/') ? currentPath.slice(1) : currentPath const index = visibleTabs.findIndex(item => { const itemPath = item.pagePath.startsWith('/') ? item.pagePath.slice(1) : item.pagePath return itemPath === path }) return index }