微信原生小程序如何自定义tabBar
流程
- app.json文件设置tabBar配置
- 根目录创建custom-tab-bar文件
app.json文件设置tabBar配置
{
"pages": [
"pages/main/main",
"pages/selfManagement/selfManagement",
"pages/guardPage/guardPage",
"pages/userCenter/userCenter"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "Weixin",
"navigationBarTextStyle": "black",
"navigationStyle": "custom"
},
"tabBar": {
"custom": true,
"list": [
{
"pagePath": "pages/main/main",
},
{
"pagePath": "pages/selfManagement/selfManagement",
},
{
"pagePath": "pages/guardPage/guardPage",
},
{
"pagePath": "pages/userCenter/userCenter",
}
]
},
"style": "v2",
"sitemapLocation": "sitemap.json"
}
根目录创建custom-tab-bar文件
index.wxml
<view class="tab-bar">
<view class="tab-bar-border"></view>
<view wx:for="{{list}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
<image lazy-load src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></image>
<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;
}
index.json
{
"component": true
}
index.js
Component({
data: {
selected: 0,
color: "#515151",
selectedColor: "#263238",
list: [
{
"pagePath": "/pages/main/main",
"text": "方案",
"iconPath": "https://homeimage.hoiyee.net/jyw6.0/lzc/jsdb/use.png",
"selectedIconPath": "https://homeimage.hoiyee.net/jyw6.0/lzc/jsdb/useA.png"
},
{
"pagePath": "/pages/selfManagement/selfManagement",
"text": "专家",
"iconPath": "https://homeimage.hoiyee.net/jyw6.0/lzc/jsdb/ask.png",
"selectedIconPath": "https://homeimage.hoiyee.net/jyw6.0/lzc/jsdb/askA.png"
},
{
"pagePath": "/pages/guardPage/guardPage",
"text": "知识",
"iconPath": "https://homeimage.hoiyee.net/jyw6.0/lzc/jsdb/study.png",
"selectedIconPath": "https://homeimage.hoiyee.net/jyw6.0/lzc/jsdb/studyA.png"
},
{
"pagePath": "/pages/userCenter/userCenter",
"text": "我的",
"iconPath": "https://homeimage.hoiyee.net/jyw6.0/lzc/jsdb/my4.png",
"selectedIconPath": "https://homeimage.hoiyee.net/jyw6.0/lzc/jsdb/my4A.png"
}
]
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url })
}
},
tabBar所需要跳转的页面
onShow() {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 2
})
}
},
tabbar自定义在第一回合选择会出现一闪一闪的现象(有解决方案的朋友,方便的话可在评论中告知,谢谢!)