小程序根据不同角色显示不同的tabbar,除了用自定义tabbar,还有其他方法吗
1条回答 默认 最新
程序猿小星 2023-06-22 12:47关注除了自定义tabbar,还有另一种方法可以根据不同角色显示不同的tabbar,这就只能使用条件渲染了
条件渲染指的是在小程序界面中,根据特定条件为页面元素设置不同的属性值。你可以使用条件渲染来为不同角色的用户显示不同的tabbar。具体实现步骤如下:- 在全局的app.js中,定义一个全局变量role,用于存储当前用户的角色。
App({ globalData: { role: '' } }) - 在登录后,获取当前用户的角色并将其存储到globalData的role变量中。
wx.login({ success: (res) => { // 发送请求获取用户信息和角色信息 wx.request({ url: 'xxx', method: 'GET', success: (res) => { // 将当前用户的角色信息存储到globalData中 getApp().globalData.role = res.data.role } }) } }) - 在app.json文件中,定义两个tabbar,分别为普通用户和管理员用户的tabbar。注意,两个tabbar的pagePath应该相同,只有iconPath和selectedIconPath不同。
{ "tabBar": { "custom": true, "list": [ { "pagePath": "pages/index/index", "iconPath": "images/home.png", "selectedIconPath": "images/home-active.png", "text": "首页" }, { "pagePath": "pages/cart/cart", "iconPath": "images/cart.png", "selectedIconPath": "images/cart-active.png", "text": "购物车" }, { "pagePath": "pages/profile/profile", "iconPath": "images/user.png", "selectedIconPath": "images/user-active.png", "text": "我的" } ] } } - 在app.js中,定义一个函数getTabBar(),根据用户角色返回不同的tabbar。该函数使用了条件渲染,如果用户角色为管理员,则返回管理员tabbar,否则返回普通用户tabbar。
const role = getApp().globalData.role function getTabBar() { if (role === 'admin') { return { "backgroundColor": "#fff", "color": "#000", "selectedColor": "#000", "borderStyle": "#eee", "list": [ { "pagePath": "pages/index/index", "iconPath": "images/home.png", "selectedIconPath": "images/home-active.png", "text": "首页" }, { "pagePath": "pages/cart/cart", "iconPath": "images/cart.png", "selectedIconPath": "images/cart-active.png", "text": "购物车" }, { "pagePath": "pages/orders/orders", "iconPath": "images/orders.png", "selectedIconPath": "images/orders-active.png", "text": "订单" }, { "pagePath": "pages/profile/profile", "iconPath": "images/user.png", "selectedIconPath": "images/user-active.png", "text": "我的" } ] } } else { return { "backgroundColor": "#fff", "color": "#000", "selectedColor": "#000", "borderStyle": "#eee", "list": [ { "pagePath": "pages/index/index", "iconPath": "images/home.png", "selectedIconPath": "images/home-active.png", "text": "首页" }, { "pagePath": "pages/cart/cart", "iconPath": "images/cart.png", "selectedIconPath": "images/cart-active.png", "text": "购物车" }, { "pagePath": "pages/profile/profile", "iconPath": "images/user.png", "selectedIconPath": "images/user-active.png", "text": "我的" } ] } } } - 最后,在每个页面的配置文件中,使用getTabBar()函数为页面设置tabBar的属性值。这里以index页面为例:
通过以上步骤,你可以根据不同角色显示不同的tabbar,而无需使用自定义tabbar。需要注意的是,使用条件渲染的方式可能需要在不同页面中重复定义getTabBar()函数,这可能会增加一些代码的复杂度{ "navigationBarTitleText": "首页", "usingComponents": {}, "tabBar": {{getTabBar()}} }
解决 无用评论 打赏 举报- 在全局的app.js中,定义一个全局变量role,用于存储当前用户的角色。