官方文档给了自定义tabbar 的方法 ,用下来感觉还是不错的。
1. 配置信息
在 app.json 中的 tabBar开启custom 字段。
所有 tab 页的 json 里需声明 usingComponents 项,也可以在 app.json 全局开启。
{
"tabBar": {
"custom": true, // 表示使用自定义 tabbar
"color": "#000000", // 可以不填 , 兼容低版本
"selectedColor": "#000000", // 可以不填 , 兼容低版本
"backgroundColor": "#000000", // 可以不填 , 兼容低版本
// 以下必填
"list": [{
"pagePath": "pages/index/index",
"text": "首页"
}, {
"pagePath": "pages/user/user",
"text": "我的"
}]
},
}
2. 添加 tabBar 代码文件
在根目录下增加文件(必须一模一样)
3.编写custom-tab-bar文件
index.wxml
<cover-view wx:if="{{showBar==true}}" class="tab-bar" bindtap="tabChange">
<cover-view data-url="/pages/index" class="tab-item {{tabIndex == 1? 'active' :''}}">首页</cover-view>
<cover-view data-url="/pages/login" class="tab-item {{tabIndex == 2? 'active' :''}}">我的</cover-view>
</cover-view>
index.js
const app = getApp()
Component({
properties: {
tabIndex:{ // 接收页面传入的数据
type:String,
value:'1'
}
},
data: {
showBar:true,
mainColorNumber: wx.getStorageSync('mainColorNumber')
},
// 组件生命周期
lifetimes: {
attached () {
},
detached () {
}
},
// 兼容v2.2.3以下写法
attached () {
},
// 挂载页面的生命周期
pageLifetimes: {
},
methods: {
tabChange(e) {
const url = e.target.dataset.url
wx.switchTab({
url
})
this.setData({
mainColorNumber: wx.getStorageSync('mainColorNumber')
})
}
}
})
index.js
{
"component": true
}
index.wxss
.tab-bar{
width: 100%;
height: 120rpx;
background-color: #FFFFFF;
color: #10272A;
position: fixed;
bottom: 0;
display: flex;
justify-content: space-between;
box-shadow: 0 0 5px #e7e7e7;
}
.tab-item{
line-height: 50px;
text-align: center;
width: 50%;
font-size: 16px;
font-weight: 600;
}
4.getTabbar的应用
在每个有tabbar的页面的js文件中增加
onShow(){
this.getTabBar().setData({
tabIndex: 2,
})
}
我index.js文件中使用到的showBar的值也可以在别的页面随时改变,也是使用getTabBar
this.getTabBar().setData({
showBar: true
})