1. 需要在app.json中的tabBar的custom设置成true;
2. 在src下的创建custom-tab-bar文件夹(和pages同级);
3. 在custom-tab-bar文件夹里面的文件编写代码;
// index.wxml
<view class="tab-bar">
<view class="tab-bar-border"></view>
//此处的wx:key也可以使用下标index 官网使用的是下标
<view wx:for="{{list}}" wx:key="item.id" class="tab-bar-item {{item.id === 2 ? 'jumped' : ''}}">
<image src="{{selected === item.id ? item.selectedIconPath : item.iconPath}}" bindtap="switchTab" data-path="{{item.pagePath}}" data-id="{{item.id}}"></image>
<view style="color: {{selected === item.id ? selectedColor : color}}">{{item.text}}</view>
</view>
</view>
//index.js
Component({
data: {
selected: 0,
"list": [{
"id": 0,
"pagePath": "/pages/index/index",
"text": "首页",
"iconPath": "/images/index.png",
"selectedIconPath": "/images/index1.png"
},
{
"id": 1,
"pagePath": "/pages/tools/index",
"text": "工具",
"iconPath": "/images/gongju.png",
"selectedIconPath": "/images/gongju1.png"
},
{
"id": 2,
"pagePath": "/pages/center/index",
"text": "",
"iconPath": "/images/huangtao.png",
"selectedIconPath": "/images/huangtao.png"
},
{
"id": 3,
"pagePath": "/pages/test/index",
"text": "题库",
"iconPath": "/images/xitiku.png",
"selectedIconPath": "/images/xitiku1.png"
},
{
"id": 4,
"pagePath": "/pages/my/index",
"text": "我的",
"iconPath": "/images/user.png",
"selectedIconPath": "/images/user1.png"
}
]
},
attached() {},
methods: {
switchTab(e) {
console.log('e', e)
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({
url
})
this.setData({
selected: data.id
})
}
}
})
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: #FF952C; */
opacity: 0.2;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 4rpx;
transform: scaleY(0.5);
/* animation: wave infinite linear 1s; */
}
.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;
}
4. 在每个pagePath的文件的index.js的onShow插入以下代码
// 修改selected的值 每个pagePath页面的selected值都是不一样的,具体以需求为准
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
selected: 2
})
}
官网地址:自定义 tabBar | 微信开放文档
自定义tabBar 写法和普通切换tab的写法基本一致,自定义tabBar 是写成了组件的形式
后续自定义tabBar遇到的问题及解决还会更新文档! 敬请期待吧!