自定义tabbar
步骤一:配置app.json文件
在app.json文件中的tabbar配置项设置"custom:true",并将所有tab页面配置在list中,即使要使用自定义tabbar,这一步也要做,以兼容低版本。
步骤二:在根目录创建一个名为custom-tab-bar的文件夹(和pages目录同级),并创建如下文件。
index.wxml内容如下:
<!-- custom-tab-bar/index.wxml -->
<view class="tab-bar">
<view wx:for="{{list}}" wx:key="index" class="tab-bar-item" bindtap="switchTab" data-index="{{index}}" data-url="{{item.pagePath}}">
<image class="tab-image" src="{{selected==index?item.selectedIconPath:item.iconPath}}"></image>
<view class="tab-text {{selected==index?'selected-color':'text-color'}}">{{item.text}}</view>
</view>
</view>
index.js内容如下:
const app=getApp()
Component({
data:{
selected:app.globalData.selected,
list:[
{
"pagePath": "/pages/homePage/homePage",
"text": "首页",
"iconPath":"/static/images/icon_home1.png",
"selectedIconPath":"/static/images/icon_home2.png"
},
{
"pagePath": "/pages/scoreShop/scoreShop",
"text": "商城",
"iconPath":"/static/images/icon_shop1.png",
"selectedIconPath":"/static/images/icon_shop2.png"
},
{
"pagePath": "/pages/foodOrder/foodOrder",
"text": "点餐",
"iconPath":"/static/images/icon_order1.png",
"selectedIconPath":"/static/images/icon_order2.png"
},
{
"pagePath": "/pages/serviceList/serviceList",
"text": "消息",
"iconPath":"/static/images/icon_info1.png",
"selectedIconPath":"/static/images/icon_info2.png"
},
{
"pagePath": "/pages/my/my",
"text": "我的",
"iconPath":"/static/images/icon_my1.png",
"selectedIconPath":"/static/images/icon_my2.png"
}
],
},
lifetimes:{
attached(){
this.setData({selected:app.globalData.selected})
}
},
methods:{
switchTab(e){
app.globalData.selected=e.currentTarget.dataset.index
//this.setData({selected:e.currentTarget.dataset.index})
wx.switchTab({
url: e.currentTarget.dataset.url
})
}
}
})
因为每个tab页都有一个tabbar实例,第一次渲染时都是使用的data中的selected作为选中态,导致了需要点两次才能成功切换的bug,为了解决这个bug,我在app.js的globalData中设置了一个selected,用来标志当前选中态,然后tabbar组件中的selected就引用globalData中的selected,然后切换页面的时候,就将globalData的selected值更改为对应的selected,并在每个tabbar实例第一次渲染时的生命周期attached中初始化各自的selected值。除了这个做法,也可以按照官网的做法:在每个tab页的onShow方法中,添加以下代码:
onShow: function () {
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
selected: 0 //如果是第二个tab页,selected就设为1,以此类推
})
}
},
index.wxss内容如下:
.tab-bar{
position: fixed;
display: flex;
bottom: 0;
left: 0;
right: 0;
height: 50px;
border-top: 1px solid #f7f7f7;
background-color: #fff;
padding-bottom: env(safe-area-inset-bottom);
}
.tab-bar-item{
flex: 1;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.tab-image{
width: 26px;
height: 26px;
}
.tab-text{
font-size: 12px;
}
.text-color{
color: #788888;
}
.selected-color{
color: #ffa520;
}
index.json内容如下:
{
"component": true
}
结果如图: