前言
真TMD坑,官方案例代码作用有限,真机演示与模拟器差异很大,需要用真机看效果
环境
win11
调试基础库2.19.4
微信开发者工具 1.06.2307250
步骤
在pages/index文件夹下建立index.wxml、index.wxss、index.js、index.json文件;twice.wxml、twice.wxss、twice.js、twice.json文件
根目录下建立custom-tab-bar文件夹,此名称为固定名,在custom-tab-bar文件夹下新建index.js、index.json、index.wxml、index.wxss文件
index.js内容:
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
//此处list配置需要注意,pagePath须为 pages/index文件夹下的文件,此处只能配置组件名
list: [
{
pagePath:"index",
iconPath: "../images/tabbar_diancan.png",
selectedIconPath: "../images/tabbar_diancan-slted.png",
text: "点餐"
},
{
pagePath: "twice",
iconPath: "../images/tabbar_order.png",
selectedIconPath: "../images/tabbar_order-slted.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.wxml内容:
<!--此处也可以使用其它UI库写界面-->
<!-- miniprogram/custom-tab-bar/index.wxml -->
<view class="tab-bar">
<view class="tab-bar-border" />
<view
wx:for="{{list}}"
wx:key="index"
class="tab-bar-item"
data-path="{{item.pagePath}}"
data-index="{{index}}"
bindtap="switchTab"
>
<image src="{{selected === index ? item.selectedIconPath : item.iconPath}}" />
<view style="color: {{selected === index ? selectedColor : color}}">{{item.text}}</view>
</view>
</view>
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 image {
width: 27px;
height: 27px;
}
.tab-bar-item view {
font-size: 10px;
}
- 在app.json中添加配置
"tabBar": {
"custom": true,
"color": "#afafaf",
"selectedColor": "#0099f6",
"backgroundColor": "#F7F8F8",
"list": [
{
"pagePath": "pages/index/index",
"iconPath": "images/tabbar_diancan.png",
"selectedIconPath": "images/tabbar_diancan-slted.png",
"text": "点餐"
},
{
"pagePath": "pages/index/twice",
"iconPath": "images/tabbar_order.png",
"selectedIconPath": "images/tabbar_order-slted.png",
"text": "订单"
}
]
},
"usingComponents": {}
- 在每个页面的onShow周期方法中添加如下代码
//若不在每个页面的周期方法中添加,则点击切换会混乱
onShow() {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 0
})
}
}