背景
当小程序原生的 tabbar 不能满足需求的时候,比如要加小红点,这时我们可以使用自定义 tabbar
使用步骤
1、新建一个tabbar组件
在根目录新建一个文件夹 custom-tab-bar(注意文件夹必须是这个命名,否则不生效),并加上以下代码:
注意:如果是框架(wepy等)则写在 src 下,并在全局进行引入,这样做是为了打包后的文件中能生成该组件,否则因为没有依赖关系打包器不会进行打包该组件
index.wxml
<!--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>
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
})
}
}
})
index.json
{
"component": true
}
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;
}
2、在 app.json 中增加定义
这里主要是加了 "custom": true
,其他的字段也要正常配置完整。
{
"tabBar": {
"custom": true,
"color": "#000000",
"selectedColor": "#000000",
"backgroundColor": "#000000",
"list": [{
"pagePath": "page/component/index",
"text": "组件"
}, {
"pagePath": "page/API/index",
"text": "接口"
}]
},
"usingComponents": {}
}
效果
遇到的坑
- 自定义组件要用 cover-view + cover-image,不要用 view
- tabBar 的相关配置只是为了兼容低版本,但这些字段不会作用于自定义 tabBar 的渲染。所以相当于要在自定义组件和配置json里写两遍。
- 可以通过
this.getTabBar()
获取当前页面的自定义 tabBar 组件实例。 - 文件夹命名必须为 custom-tab-bar,并且不用在页面中引入,系统会自动识别。