前言
真TMD坑,官方案例代碼作用有限,真機(jī)演示與模擬器差異很大,需要用真機(jī)看效果
環(huán)境
win11
調(diào)試基礎(chǔ)庫2.19.4
微信開發(fā)者工具 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內(nèi)容:
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: "點(diǎn)餐"
},
{
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內(nèi)容:
{
"component": true
}
index.wxml內(nèi)容:
<!--此處也可以使用其它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內(nèi)容:
.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": "點(diǎn)餐"
},
{
"pagePath": "pages/index/twice",
"iconPath": "images/tabbar_order.png",
"selectedIconPath": "images/tabbar_order-slted.png",
"text": "訂單"
}
]
},
"usingComponents": {}
- 在每個(gè)頁面的onShow周期方法中添加如下代碼
//若不在每個(gè)頁面的周期方法中添加,則點(diǎn)擊切換會混亂
onShow() {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 0
})
}
}