该功能在小程序中应用场景多为根据不能角色来展示不同的tabBer, 解决方案可参考小程序官方 自定义tabBar: https://developers.weixin.qq.com/miniprogram/dev/framework/ability/custom-tabbar.html
注意:tabBer中不能使用分包路径,如果需要建议主包添加跳转路径 内容放分包中。 即(a页面放在主包 通过a页面跳转至分包页面
)
1. 创建
在项目目录下新建custom-tab-bar文件夹,如何再文件夹中新建 index.js ,index.json index.wxml ,index.wxss
目录结构
custom-tab-bar/index.js
custom-tab-bar/index.json
custom-tab-bar/index.wxml
custom-tab-bar/index.wxss
也可以拿微信小程序官方的示例
2. 配置信息
2.1 在app.json 中的 tabBar中加上custom:true;
2.2 在所需要tabBar的页面的josn中要都加上"usingComponents": {},也可直接在app.json中直接全局开启
注意:即使使用自定义 tabBar 也要保证app.json中的tabBar至少有两项默认的页面
示例代码 app.json
{
"tabBar": {
"custom": true,
"color": "#000000",
"selectedColor": "#000000",
"backgroundColor": "#000000",
"list": [{
"pagePath": "page/component/index",
"text": "组件"
}, {
"pagePath": "page/API/index",
"text": "接口"
}]
},
"usingComponents": {}
}
3. 配置 custom-tab-bar/index.js
在data中要加上allList 用来存放不同角色所需要的 tabBar 页面
const app = getApp();
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [],
allList:{
// 角色1 tabBar
'boss':[{
pagePath: "/index/index",
iconPath: "/image/icon_component.png",
selectedIconPath: "/image/icon_component_HL.png",
text: "组件(boss)"
}, {
pagePath: "/index/index2",
iconPath: "/image/icon_API.png",
selectedIconPath: "/image/icon_API_HL.png",
text: "接口(boss)"
}],
// 角色2 tabBar
'user':[{
pagePath: "/index/index",
iconPath: "/image/icon_component.png",
selectedIconPath: "/image/icon_component_HL.png",
text: "组件(user)"
}, {
pagePath: "/index/index2",
iconPath: "/image/icon_API.png",
selectedIconPath: "/image/icon_API_HL.png",
text: "接口(user)"
}]
}
},
attached() {
// 获取缓存中的用户信息 如果用户已经登录过就直接设置tabbar
// 获取缓存这一步可以不需要(只需要保证每次切换用户时都能调用app.changName方法即可)
let usertypename = wx.getStorageSync('userTypeName')
if(!!usertypename){
this.setData({
list:this.data.allList[usertypename]
})
}
//为app.js 定义函数 用来切换用户信息时调用
app.changName = res => {
//res 为用户信息类型 res == usertypename
this.setData({
list:this.data.allList[res]
})
}
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
this.setData({
selected: data.index
})
}
}
})
4.使用的页面
要在使用该tabbar 的页面js上都要加
Component({
pageLifetimes: {
show() {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 0
})
}
}
}
})
5.切换用户
可在获取用户信息后执行该方法(注意需要等待custom-tab-bar/index.js 中app.changName 定义生效)
this.changName('boss')