📃个人主页:编程的一拳超人
⛺️ 欢迎关注:👍点赞 👂🏽留言 😍收藏 💞 💞 💞
于高山之巅,方见大河奔涌;于群峰之上,更觉长风浩荡。
小程序可以根据用户的不同显示不同的导航栏,这通常通过自定义底部导航栏(tabBar)来实现。以下是实现这一功能的主要步骤和要点:
一、配置全局文件
在小程序的全局配置文件app.json中,需要将tabBar的custom属性设置为true,以启用自定义底部导航栏。例如:
{"tabBar":{"custom":true,// 其他tabBar配置,如颜色、背景色等}}二、创建自定义导航栏组件
- 在项目的根目录下或与
/pages同级的目录下,创建一个名为custom-tab-bar的文件夹。 - 在
custom-tab-bar文件夹中,创建组件的四个文件:index.js、index.json、index.wxml和index.wxss。
三、编写组件代码
1.index.js
在index.js中,定义组件的数据、属性和方法。数据部分可以包括当前选中的导航项、导航项列表(根据用户角色动态生成)等。例如:
Component({data:{selected:0,// 当前选中的导航项索引color:"#000000",roleId:wx.getStorageSync('roleId'),// 从缓存中获取用户角色IDselectedColor:"#1396DB",allList:[{list1:[// 用户A的底部导航栏{"text":"首页","pagePath":"/pages/index/index","iconPath":"/images/01.png","selectedIconPath":"/images/01_select.png"},{"text":"我的","pagePath":"/pages/person/person","iconPath":"/images/03.png","selectedIconPath":"/images/03_select.png"}],list2:[// 用户B的底部导航栏{"text":"订单","pagePath":"/pages/order/order","iconPath":"/images/04.png","selectedIconPath":"/images/04_select.png"},{"text":"个人","pagePath":"/pages/person/trader","iconPath":"/images/03.png","selectedIconPath":"/images/03_select.png"}]}],list:[]// 当前显示的导航项列表},attached(){// 根据用户角色设置导航项列表if(this.data.roleId===0){this.setData({list:this.data.allList[0].list1});}elseif(this.data.roleId===1){this.setData({list:this.data.allList[0].list2});}wx.setStorageSync('list',this.data.list);// 将导航项列表存入缓存},methods:{switchTab(e){// 切换导航项constdata=e.currentTarget.dataset;constpath=data.path;this.setData({selected:data.index});wx.switchTab({url:path});}}});2.index.json
在index.json中,声明该组件为自定义组件:
{"component":true,"usingComponents":{}}3.index.wxml
在index.wxml中,使用<cover-view>和<cover-image>等标签来渲染导航栏。例如:
<cover-viewclass="tab-bar"><cover-viewclass="tab-bar-border"></cover-view><cover-viewwx:for="{{list}}"wx:key="index"class="tab-bar-item"data-path="{{item.pagePath}}"data-index="{{index}}"bindtap="switchTab"><cover-imageclass="cover-image"src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></cover-image><cover-viewclass="tab-bar-text"style="color:{{selected === index ?selectedColor:color}}">{{item.text}}</cover-view></cover-view></cover-view>4.index.wxss
在index.wxss中,定义导航栏的样式。例如:
.tab-bar{position:fixed;bottom:0;left:0;right:0;display:flex;justify-content:space-around;background-color:#ffffff;border-top:1px solid #ebebeb;}.tab-bar-item{flex:1;text-align:center;padding-top:10px;}.cover-image{width:25px;height:25px;}.tab-bar-text{font-size:12px;}四、使用自定义导航栏组件
在小程序的每个需要使用自定义导航栏的页面中,都需要在页面的json文件中声明使用该组件。例如:
{"usingComponents":{"custom-tab-bar":"/custom-tab-bar/index"}}同时,在页面加载时(如onLoad或onShow方法中),需要调用自定义导航栏组件的方法来更新选中状态(如果需要的话)。
五、用户角色判断与导航栏更新
在用户登录或角色发生变化时(如从用户A切换到用户B),需要更新用户角色ID(可以存储在全局变量或缓存中),并重新加载自定义导航栏组件以显示正确的导航项列表。这可以通过在小程序的app.js中监听用户登录状态变化或使用全局事件来实现。
通过以上步骤,就可以实现小程序根据用户的不同显示不同的导航栏了。需要注意的是,在实际开发中可能还需要根据具体需求进行进一步的优化和调整。