1.配置tabBar
- 在 app.json 中的 tabBar 项指定 custom 字段,同时其余 tabBar 相关配置也补充完整。
- 所有 tab 页的 json 里需声明 usingComponents 项,也可以在 app.json 全局开启
{
"tabBar": {
"custom": true,
"color": "#000000",
"selectedColor": "#000000",
"backgroundColor": "#000000",
"list": [{
"pagePath": "page/component/index",
"text": "组件"
}, {
"pagePath": "page/API/index",
"text": "接口"
}]
},
"usingComponents": {}
}
2.添加 tabBar 代码文件
在代码根目录下添加入口文件:
custom-tab-bar/index.js
custom-tab-bar/index.json
custom-tab-bar/index.wxml
custom-tab-bar/index.wxss
3. 编写 tabBar 代码
用自定义组件的方式编写即可,该自定义组件完全接管 tabBar 的渲染。另外,自定义组件新增 getTabBar
接口,可获取当前页面下的自定义 tabBar 组件实例
custom-tab-bar 代码
<!--miniprogram/custom-tab-bar/index.js-->
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [{
pagePath: "/index/index",
iconPath: "/image/icon_component.png",
selectedIconPath: "/image/icon_component_HL.png",
text: "组件"
}, {
pagePath: "/index/index2",
iconPath: "/image/icon_API.png",
selectedIconPath: "/image/icon_API_HL.png",
text: "接口"
}]
},
attached() {
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
this.setData({
selected: data.index
})
console.log(this.selected)
}
}
})
<!--miniprogram/custom-tab-bar/index.wxml-->
<cover-view class="tab-bar">
<cover-view class="tab-bar-border"></cover-view>
<cover-view wx:for="{{list}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
<cover-image src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></cover-image>
<cover-view style="color: {{selected === index ? selectedColor : color}}">{{item.text}}</cover-view>
</cover-view>
</cover-view>
css样式仅供参考
<!--miniprogram/custom-tab-bar/index.wxss-->
.tab-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 48px;
background: white;
display: flex;
padding-bottom: env(safe-area-inset-bottom);
}
.tab-bar-border {
background-color: rgba(0, 0, 0, 0.33);
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 1px;
transform: scaleY(0.5);
}
.tab-bar-item {
flex: 1;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.tab-bar-item cover-image {
width: 27px;
height: 27px;
}
.tab-bar-item cover-view {
font-size: 10px;
}
完成后发现一个问题,点击切换路由后tab不能及时切换正确还发生页面闪烁情况
解决办法是:
在切换路由的每个页面的onShow生命周期函数里修改custom-tab-bar里的selected值(即切换tab的index)
onShow: function () {
this.getTabBar().setData({
selected: 0
});
}
问题就解决啦!
网友评论