小程序自定义tabBar组件 父子通信原理

创建一个tabBar文件
tabBar.wxml
在这里插入图片描述

tabBar.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 cover-image {
width: 27px;
height: 27px;
}

.tab-bar-item cover-view {
font-size: 10px;
}

tabBar.json
{
“component”: true
}

tabBar.js
Component({
properties: {
propSelected: Number
},
data: {
selected: 0,
color: “#7A7E83”,
selectedColor: “#3cc51f”,
list: [{
pagePath: “/pages/index/index”,
iconPath: “…/resources/icon_home.png”,
selectedIconPath: “…/resources/icon_home_selected.png”,
text: “首页”
}, {
pagePath: “/pages/mine/mine”,
iconPath: “…/resources/icon_mine.png”,
selectedIconPath: “…/resources/icon_mine_selected.png”,
text: “我的”
}]
},
attached() {
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
this.setData({
selected: data.index
})
}
}
})

app.json文件配置
{
“pages”: [
“pages/index/index”,
“pages/logs/logs”,
“pages/mine/mine”
],
“window”: {
“backgroundTextStyle”: “light”,
“navigationBarBackgroundColor”: “#fff”,
“navigationBarTitleText”: “Weixin”,
“navigationBarTextStyle”: “black”
},
“tabBar”: {
“custom”: true,
“color”: “#7A7E83”,
“selectedColor”: “#3cc51f”,
“borderStyle”: “black”,
“backgroundColor”: “#ffffff”,
“list”: [
{
“pagePath”: “pages/index/index”,
“iconPath”: “resources/icon_home.png”,
“selectedIconPath”: “resources/icon_home_selected.png”,
“text”: “首页”
},
{
“pagePath”: “pages/mine/mine”,
“iconPath”: “resources/icon_home.png”,
“selectedIconPath”: “resources/icon_home_selected.png”,
“text”: “我的”
}
]
},
“usingComponents”: {},
“style”: “v2”,
“sitemapLocation”: “sitemap.json”
}

页面引用,示例:
index.wxml

index.json
{
“navigationBarBackgroundColor”: “#eee”,
“navigationBarTitleText”: “首页”,
“navigationBarTextStyle”: “black”,
“usingComponents”: {
“custom-tab-bar”: “…/custom-tab-bar/custom-tab-bar”
}
}

mine.wxml

mine.json
{
“navigationBarBackgroundColor”: “#eee”,
“navigationBarTitleText”: “首页”,
“navigationBarTextStyle”: “black”,
“usingComponents”: {
“custom-tab-bar”: “…/custom-tab-bar/custom-tab-bar”
}
}

该组件使用了父子通信原理
例如:
父:index.wxml
prop绑定一个属性,并设置值 prop-selected=“0”

子组件:tabBar.wxml 通过properties 获取传来的值,并应用于页面 properties: { propSelected: Number },