一、官方文档
?自定义 tabBar | 微信开放文档
根据官方的案例,做了自己的案例测试,效果图如下
二、在app.json里面添加tabBar配置
"pages":[
"pages/index/index",
"pages/logs/logs",
"pages/goods/index"
],
"tabBar": {
"custom": true,
"color": "#000000",
"selectedColor": "#000000",
"backgroundColor": "#000000",
"list": [{
"pagePath": "pages/index/index",
"text": "首页"
}, {
"pagePath": "pages/goods/index",
"text": "商品"
}]
}
配置完成后,不会出现tabBar,需要在custom-tab-bar这个微信小程序已经定义的文件夹,里面添加对应的路径配置
三、在custom-tab-bar添加配置
1. 在custom-tab-bar创建如下目录
custom-tab-bar/index.js
custom-tab-bar/index.json
custom-tab-bar/index.wxml
custom-tab-bar/index.wxss
2.给index.wxml添加tabBar的结构代码 ?
<!--miniprogram/custom-tab-bar/index.wxml-->
<cover-view class="tab-bar">
<cover-view class="tab-bar-border"></cover-view>
<cover-view wx:for="{{list}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
<cover-image src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></cover-image>
<cover-view style="color: {{selected === index ? selectedColor : color}}">{{item.text}}</cover-view>
</cover-view>
</cover-view>
3.?给index.js 添加数据配置 和 事件方法
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [{
pagePath: "/pages/index/index",
iconPath: "/image/home2_icon.png",
selectedIconPath: "/image/home1_icon.png",
text: "首页"
}, {
pagePath: "/pages/goods/index",
iconPath: "/image/readTrain2_icon.png",
selectedIconPath: "/image/readTrain1_icon.png",
text: "商品"
}]
},
attached() {
},
methods: {
switchTab(e) {
console.log("执行跳转",e);
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
this.setData({
selected: data.index
})
}
}
})
4.?给index.wxss 添加样式
/* custom-tab-bar/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 cover-image {
width: 27px;
height: 27px;
}
.tab-bar-item cover-view {
font-size: 10px;
}
此时,通过点击切换页面,就可以实现
=》如果在选择点击切换按钮时,页面没根据tabBar进行切换,问题很可能能在custom-tab-bar目录的index.js 的list数据配置的页面路径,一定要/ 开头,如/pages/goods/index ,这才能找到页面。
四、tabbar图标切换 要点击两次才能有选中状态
在`/pages/index目录的index.js文件,的onShow生命周期方法,添加如下代码
onShow() {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
//唯一标识(其它设置不同的整数)
selected: 0
})
}
},
在pages/goods/ 目录的index.js文件,的onShow生命周期方法,添加如下代码,
onShow() {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
//唯一标识(其它设置不同的整数)
selected: 1
})
}
},
注意:预览时,提示登陆的用户不是小程序的开发者,可添加appid。
|