在微信小程序开发中,TabBar 是用户体验的重要组成部分。默认的 TabBar 样式可能无法满足所有应用的需求,因此自定义 TabBar 成为了一种趋势。本篇文章将带你一步步实现自定义 TabBar,同时分享一些在开发过程中遇到的问题和解决方案。
首先,确保在 app.json
中配置 custom
属性,启用自定义 TabBar。
{
"tabBar": {
"custom": true
}
}
在项目根目录中,创建一个名为 custom-tab-bar 的组件。需要创建以下文件:
custom-tab-bar/index.js
custom-tab-bar/index.json
custom-tab-bar/index.wxml
custom-tab-bar/index.wxss
在 index.js 中,实现 TabBar 的逻辑:
// custom-tab-bar/index.js
Component({
data: {
rightId: wx.getStorageSync("rightId") || 0,
list: [{
"pagePath": "/pages/index/index",
"iconPath": "../img/1.png",
"selectedIconPath": "../img/1-1.png",
"text": "Page1"
},
{
"pagePath": "/pages/page2/index",
"iconPath": "../img/2.png",
"selectedIconPath": "../img/2-1.png",
"text": "Page2"
}],
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset;
const url = data.path;
wx.switchTab({ url });
this.setData({ selected: data.index });
}
}
});
在 index.json 中配置组件:
{
"component": true,
"usingComponents": {}
}
在 index.wxml 中编写 TabBar 的视图结构:
<cover-view class="tab-bar" wx:if="{{tabBarShow}}">
<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>
2.4 index.wxss
在 index.wxss 中添加样式:
/* 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;
}
在一些情况下,可能需要隐藏 TabBar 以避免与其他控件(例如选择器)冲突。
例如:
可以通过以下代码实现:
在custom-tab-bar中增加变量:
tabBarShow: true
<picker bind:tap="openPicker" mode="selector" range="{{machineTypeList}}" value="{{reportDetail.machineType}}" data-field="machineType" bindchange="formInputChange" bindcancel="clearTabTar">
<van-icon style="font-size: 27px;display: block;color: #4F81BD;" name="weapp-nav" />
picker>
openPicker() {
this.getTabBar().setData({
tabBarShow: false
});
},
clearTabTar() {
this.getTabBar().setData({
tabBarShow: true
});
}
在所有tabbar对应的页面中的show方法中添加:
if (typeof this.getTabBar === "function" &&
this.getTabBar()) {
this.getTabBar().setData({
selected: num //num对应的是页面位居tabbar的下标
})
}
通过以上步骤,成功实现了自定义 TabBar,并且能够根据需要控制其显示与隐藏。这种自定义方式不仅提升了用户体验应用更加灵活。希望这篇博客能对你在微信小程序开发中有所帮助!