微信小程序相关开发文档链接:
https://developers.weixin.qq.com/miniprogram/dev/framework/ability/custom-tabbar.html
微信小程序 原生框架(非uni)自定义tabbar
1、app.json里面tabBar添加配置 custom:true,其他和非自定义设置一样
{
"tabBar": {
"custom": true,
"color": "#000000",
"selectedColor": "#000000", //tab选中颜色
"backgroundColor": "#000000",
"list": [{ //每个tab对应的路由路径
"pagePath": "page/component/index",//此处page前面未加/
"text": "组件"
}, {
"pagePath": "page/API/index",
"text": "接口"
}]
},
"usingComponents": {}
}
2、在项目根文件目录下新建文件夹custom-tab-bar(名字必须为这个,该文件夹与app.js同级,必须)
3、编辑custom-tab-bar文件 自定义tab相关内容
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
src="{{selected === index ? item.selectedIconPath : item.iconPath}}"
></image>
<view style="color: {{selected === index ? selectedColor : color}}" wx:if="{{item.text}}"
>{{item.text}}</view
>
</view>
</view>
wxss文件
.tab-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;//注意这里的tab的高度单位为px
background: white;
display: flex;
flex-direction: row;
padding-bottom: env(safe-area-inset-bottom);
pointer-events: auto;
}
.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: 24px;
height: 24px;
}
js文件
Component({
data: {
selected: 0, //重要,切换过程中用到
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [{
pagePath: "/index/index", //注意
iconPath: "/image/icon_component.png",
selectedIconPath: "/image/icon_component_HL.png",
text: "组件"
}, {
pagePath: "/index/index2",
iconPath: "/image/icon_API.png",
selectedIconPath: "/image/icon_API_HL.png",
text: "接口"
}]
},
attached() {
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
this.setData({
selected: data.index
})
}
}
})
4、在每个tab对应的路径文件中,组件onShow生命周期里设置tabbar选中select
onShow(options) {
if (typeof this.getTabBar === 'function') {
this.getTabBar((tabBar) => {
tabBar.setData({
selected: 0 //这个值,根据当前路由所处是tabbar的list数组的index
})
})
}
},
5.每个tabbar对应的路由页面,page最好加入padding-bottom:calc(env(safe-area-inset-bottom) + 24rpx + 50px); 50是设置的tabbar的高度,24是留余的页面空白