在网上找了很多自定义tabbar的例子很多都是定义组件然后在需要tabbar的页面底部放置组件,这样导致页面加载的时候tabbar也会跟着重新加载网络卡顿是影响用户体验。
根据官方文档tabbar自定义其实很简单
微信官方文档自定义tabbar
自己做了个简单的例子方便以后看
1.项目根目录创建custom-tab-bar文件夹
2.index.js文件定义组件内容
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [
{
"pagePath": "/pages/index/index",
"iconPath": "/image/icon_API.png",
"selectedIconPath": "/image/icon_API_HL.png",
"text": "组件"
},
{
"pagePath": "/pages/home/index",
"iconPath": "/image/home_default.png",
"selectedIconPath": "/image/home_select.png",
"text": ""
},
{
"pagePath": "/pages/logs/logs",
"iconPath": "/image/icon_component.png",
"selectedIconPath": "/image/icon_component_HL.png",
"text": "接口"
}
]
},
attached() {
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset;
const url = data.path;
wx.switchTab({url})
}
}
})
3.index.json定义组件
{
"component": true
}
4.index.wxml页面内容
<view class="tab-bar">
<block wx:for="{{list}}" wx:key="index">
<view class="{{index==1?'grid-item2':'grid-item'}}" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
<view class="view-center">
<image class="{{index==1?'img-size2':'img-size'}}" src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></image>
</view>
<view class="view-center">
<text style="color: {{selected === index ? selectedColor : color}};font-size: 10px;">{{item.text}}</text>
</view>
</view>
</block>
</view>
5.index.wxss页面样式
.tab-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;
background: white;
display: flex;
padding-bottom: env(safe-area-inset-bottom);
border: 3rpx solid #DDDDDD;
}
.view-center{
display: flex;
justify-content: center;
align-items: center;
}
.grid-item{
width: 33%;
height: 50px;
margin-top: 10px;
}
.grid-item2{
width: 33%;
height: 50px;
margin-top:-25px;
}
.img-size{
width: 25px;
height: 25px;
}
.img-size2{
width: 80px;
height: 80px;
}
6.app.json内tabbar属性加一个
7.tabbar页面内的onLoad
onLoad(options) {
//确保selected能够指定到对应的图标
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 1
})
}
},