在小程序开发时,在app.json中配置底部tabBar无法满足我现有的需求,所以准备自己定义一个tabBar.
1.app.json中配置
"tabBar": {
"custom":true, // 支持自定义tabBar
"list":[ // 至少包含两个tab信息
{
"pagePath": "pages/staffs/staffs",
"text": "机构",
"iconPath": "./assets/common/staff-default.png",
"selectedIconPath": "./assets/common/staff-active.png"
},
{
"pagePath": "pages/activity/activity",
"text": "活动",
"iconPath": "./assets/common/activity-default.png",
"selectedIconPath": "./assets/common/activity-active.png"
}
]
}
2.编写我们需要的内容
2.1 index.html
index.html
<!--custom-tab-bar/index.wxml-->
<cover-view class="tTabBar">
<cover-view
class="tTabBar-item"
wx:for="{{list}}"
wx:key="index"
bindtap="switchLab"
data-jumpPath="{{item.pagePath}}"
data-index="{{index}}"
>
<cover-image class="tTabBar-item-image" src="{{selected === index?item.selectedIconPath:item.iconPath}}" />
<cover-view class="tTabBar-item-name" style="{{selected === index?'color:#1890FF':''}}">
{{item.text}}
</cover-view>
</cover-view>
</cover-view>
2.2 index.less
.tTabBar{
padding-bottom: constant(safe-area-inset-bottom); /* 兼容 iOS < 11.2 */
padding-bottom: env(safe-area-inset-bottom); /* 兼容 iOS >= 11.2 */
position: absolute;
bottom: 0;
display: flex;
width: 100%;
justify-content: space-between;
height: 100rpx;
background: #ffffff;
&-item{
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
flex-shrink: 0;
&-image{
display: inline-block;
width: 48rpx;
height: 48rpx;
margin-bottom: 8rpx;
}
&-name{
font-size: 20rpx;
line-height: 28rpx;
color: #999999;
}
}
}
2.3 index.js
// custom-tab-bar/index.js
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
selected:0,
color: "#999999",
selectedColor: "#1990FF",
position: "bottom",
borderStyle: "white",
list: [
{
"pagePath": "/pages/staffs/staffs",
"text": "机构",
"iconPath": "../assets/common/staff-default.png",
"selectedIconPath": "../assets/common/staff-active.png"
},
{
"pagePath": "/pages/tejia/tejia",
"text": "精选课",
"iconPath": "../assets/common/tejia-default.png",
"selectedIconPath": "../assets/common/tejia-active.png"
},
{
"pagePath": "/pages/activity/activity",
"text": "活动",
"iconPath": "../assets/common/activity-default.png",
"selectedIconPath": "../assets/common/activity-active.png"
}
]
},
/**
* 组件的方法列表
*/
methods: {
// 切换tab
switchLab:async function(e){
const {jumppath,index} = e.currentTarget.dataset;
wx.switchTab({
url: jumppath,
})
this.setData({
selected:index,
})
}
},
observers:{
}
})
3.会遇到的问题
3.1 跳转时页面闪烁,高亮存在问题
- 在list中每一个页面中设置,在页面显示时,动态设置一下getTabBar获得组件中的selected值,这样也确保了入口不固定时,每次高亮的tabBar都是正确的
onShow: function () {
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({ // 文档中有介绍 getTabBar用于获取当前组件实例
selected: 2
})
}
},
总结用法,希望可以帮助到你,
我是Ably,你无须超越谁,只要超越昨天的自己就好~