在微信小程序中,可以通过实现自定义 tabBar
来满足复杂的布局需求。以下是实现步骤和具体方法:
一、配置 app.json
在项目的 app.json
中启用自定义 tabBar
:
"tabBar": {
"custom": true,
"color": "#7A7E83",
"selectedColor": "#3cc51f",
"borderStyle": "black",
"backgroundColor": "#ffffff",
"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": "接口"
}
]
}
关键点:
"custom": true
表示启用自定义 tabBar。list
中的pagePath
必须与页面路径一致。
二、 创建自定义 tabBar
组件
新建一个目录,例如 custom-tabbar
,用于存放自定义 tabBar 的代码。
编辑
custom-tab-bar
├── index.json
├── index.wxml
├── index.wxss
├── index.js
1.配置文件 index.json
:
{
"component": true
}
2.模板文件 index.wxml
:
<!--miniprogram/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 src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></image>
<view style="color: {{selected === index ? selectedColor : color}}">{{item.text}}</view>
</view>
</view>
3.样式文件 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;
}
4.脚本文件 index.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
})
}
}
})
三、在页面中使用自定义 tabBar
为需要显示 tabBar 的页面添加以下内容:
1.页面 WXML 示例:
<view class="intro">组件</view>
2.页面 JSON 示例:
{
"usingComponents": {}
}
3.页面 WXSS 示例:
.intro {
margin: 30px;
text-align: center;
}
4.页面 JS 示例:
Component({
pageLifetimes: {
show() {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 0
})
}
}
}
})
四、官方文档
例如上面操作还是不懂,可以直接去官方
自定义 tabBar | 微信开放文档
下载里面demo一探究竟!