在百度上搜索了很久的關(guān)于微信小程序自定義tabbar組件如何實(shí)現(xiàn)纺酸,幾乎沒(méi)有一個(gè)比較全面的解答吱瘩,故此將整體的流程記錄下來(lái)。
1、首先按照官方組件在app.json中定義tabbar
app.json中配置如下:
"tabBar": {
"custom": true,
"backgroundColor": "#FFFFFF",
"borderStyle": "white",
"list": [
{
"pagePath": "pages/index/index",
"text": "首頁(yè)",
"iconPath": "./images/home.png",
"selectedIconPath": "./images/home.png"
},
{
"pagePath": "pages/me/me",
"text": "個(gè)人中心",
"iconPath": "./images/me.png",
"selectedIconPath": "./images/me.png"
}
]
},
"usingComponents": {}
2、在項(xiàng)目根目錄創(chuàng)建自定義tabbar組件,劃重點(diǎn):根目錄槽卫,請(qǐng)看下圖拿诸,不放根目錄會(huì)導(dǎo)致this.getTabBar = null
image.png
組件的名稱也和官方文檔保持一致扒袖,不要自定義
3、組件內(nèi)容如下:
- custom-tab-bar/index.js
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [{
pagePath: "../../pages/index/index",
iconPath: "../images/home.png",
selectedIconPath: "../images/home.png",
text: "首頁(yè)"
}, {
pagePath: "../../pages/me/me",
iconPath: "../images/me.png",
selectedIconPath: "../images/me.png",
text: "個(gè)人中心"
}]
},
attached() {
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
this.setData({
selected: data.index
})
}
}
})
- custom-tab-bar/index.json
{
"component": true
}
- 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>
- 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;
}
4亩码、在pages下的各個(gè)頁(yè)面組件引入tabbar季率,以首頁(yè)舉例:
- pages/index.json
{
"usingComponents": {
"custom-tab-bar": "../../custom-tab-bar/index"
}
}
- pages/index.js
Page({
onShow: function () {
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
selected: 0
})
}
}
})
- pages/index.wxml
<view class="container">
<custom-tab-bar></custom-tab-bar>
</view>