我们项目中有一个需求:
也就是说,tabbar的“分类”项会应该需求显示为“分类”/“管理台”,我们的tabbar项已经有5个,再加上一个就是6个。小程序规定tabbar中的list项不能超过5个。而且,小程序未提供显示/隐藏tabbar某一项的功能。
我们知道小程序2.7.0版本增加了一个API(wx.setTabBarItem(Object object))用于动态设置tabbar某一项的内容。但是有一个问题,无法设置pagePath。相关API:https://developers.weixin.qq.com/miniprogram/dev/api/ui/tab-bar/wx.setTabBarItem.html
既然此路不通,我就考虑采用自定义tabbar的模式来实现想要的功能。
方案一:采用小程序官方网站提供的自定义模式(全局app.json中的custom设置为true),相关地址:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/custom-tabbar.html
页面js中,不管是采用component中的pageLifetimes-show()还是采用page中的onshow,都会出现莫名其妙的问题,其中最常见的就是闪烁的问题。
//Component方法
Component({
pageLifetimes: {
show() {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 2
})
}
}
}
})
//Page方法
Page({
onShow: function () {
console.log(!this.getTabBar())
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 2
})
}
}
})
方案二:app.json中不设置custom值,通过设置页面json中的usingComponents值
//wxml文件
<custom-tab-bar curActiveIndex="0"></custom-tab-bar>
//js文件
Page({
onLoad: function (options) {
wx.hideTabBar({
animation: false,
})
}
})
//json文件
{
"usingComponents": {
"custom-tab-bar": "/componets/customTabBar/index"
}
}
//customTabBar/index.js
Component({
properties: {
curActiveIndex: {
type: Number,
default: 0
}
},
data: {//自定义tabbar内容},
attached() {
this.setData({
selected: this.data.curActiveIndex
})
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
// this.setData({
// selected: data.index
// })
}
}
})
结果显示:第一次加载tabbar页面,虽然会有闪烁现象,但影响很小,可以忽略不计。
这一步走通了,接下来我想要改变连接地址:
attached() {
let a = {pagePath: "/pages/manager/index", text: "管理台", iconPath: "/images/tabbar/bottom_tab_02.png", selectedIconPath: "/images/tabbar/bottom_tab_02_active.png"}
this.setData({
[`list[2]`]: a,
selected: this.data.curActiveIndex
})
},
点击tabbar中“管理台”,结果发现:
提示不是tabbar页面,也就是未注册“管理台”项为tabbar。然后,我试着在app.json中修改“分类”pagePath为“管理台”pagePath,居然不报错了,而且还能跳转成功。前面,我们说到了tabbar不允许超过5个,而且无法隐藏某一项。所以,这个自定义tabbar也是无法实现我们的需求了。
难道就没有办法了吗?然而,天无绝人之路。峰回路转……
一个折中的办法,就是通过设置一个tabbar页面进行中转。默认设置pagePath为中转页面的地址,将要跳转的页面设置为组件的形式,在中转页面中控制其加载。
//app.js
App({
onLaunch: function () {
wx.setTabBarItem({
index: 2,
text: '管理台'
})
}
})
//中转页面.js
Page({
data: {
showPages: 'manager'
}
})
//中转页面.json
{
"usingComponents": {
"category-list-tab": 分类页面地址,
"manager": 管理台页面地址
}
}
//中转页面.wxml
<manager wx:if="{{showPages === 'manager'}}">
管理台内容
</manager>
<category-list-tab wx:else>
分类内容
</category-list-tab>
完美解决!具体页面中的数据请求,我就不细说了!不知道各位同仁是否有更好的解决方案,欢迎提出异议~谢谢!!!