解决图标点击两次才能选中状态
第一步、在全局 app.json
中开启"custom": true
,并运用组件usingComponents
"tabBar": {
"custom": true,
"color": "#6e6d6b",
"selectedColor": "#409EFF",
"borderStyle": "black",
"backgroundColor": "#fff",
"list": [
{
"pagePath": "pages/index/index",
"iconPath": "images/home-off.png",
"selectedIconPath": "images/home-on.png",
"text": "首页"
},
{
"pagePath": "pages/my/my",
"iconPath": "images/my-off.png",
"selectedIconPath": "images/my-on.png",
"text": "我的"
}
]
},
"usingComponents": {
"custom-tab-bar":"/components/custom-tab-bar/index"
}
第二步、自定义子组件tabbar
,在根目录componets
下创建custom-tab-bar [ 名字不要变,必须是这个 ]
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>
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 {
position: relative;
height: 45px;
flex: 1;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.tab-bar-item image {
position: absolute;
top: 2px;
left: 50%;
transform: translateX(-50%);
width: 27px;
height: 27px;
}
.tab-bar-item view {
font-size: 10px;
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
index.js
两处与微信官方文档不同之处已在下面代码中注释出来
Component({
//1.不同部分定义 properties
properties:{
selected:{
type:Number,
value:null
}
},
data: {
selected: 0,
color: "#6e6d6b",
selectedColor: "#409EFF",
borderStyle: "black",
backgroundColor: "#fff",
list: [{
pagePath: "/pages/index/index",
iconPath: "/images/home-off.png",
selectedIconPath: "/images/home-on.png",
text: "首页"
}, {
pagePath: "/pages/my/my",
iconPath: "/images/my-off.png",
selectedIconPath: "/images/my-on.png",
text: "我的"
}]
},
attached() {
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
this.setData({
// 2.不同部分使用 properties 中定义数据
selected: this.properties.selected
})
}
}
})
第三步、在页面中使用
<custom-tab-bar selected="{{selectedTab}}"></custom-tab-bar>
并在js文件中定义属性,根据页面位置
selectedTab: 0