微信自定义tabBar方法
环境
由于项目需求,微信原本的tabbar样式无法满足,项目需求tabBar底部只放置图片,不显示文字,并且间距大小需要自定义。所以需要自定义tabBar实现效果
封装组件
//封装组件tabBarCom
//wxml
<view class="tab-bar">
<view class="tab-item {{selected === index ? 'selected' : ''}}" wx:for="{{tabs}}" wx:key="{{index}}" bindtap="onTabItemTap" data-index="{{index}}">
<image class="icon" src="{{selected === index ? item.selectedIcon : item.icon}}" />
</view>
</view>
//wxss
.tab-bar {
display: flex;
width: 100%;
height: 50px;
background-color: #fff;
}
.tab-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: #666;
}
.tab-item.selected {
color: #007aff; /* 选中状态的文本颜色 */
}
.icon {
width: 48px;
height: 49px;
}
.title {
font-size: 12px;
margin-top: 5px;
}
//js
Component({
/**
* 组件的属性列表
*/
properties: {
tabs: {
type: Array,
value: []
},
selected: {
type: Number,
value: 0,
observer(newVal) {
this.setData({
selected: newVal
});
}
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
onTabItemTap: function(e) {
const index = e.currentTarget.dataset.index;
// 触发自定义事件,通知父组件当前选择的页签项
this.triggerEvent('change', { index });
}
}
})
page内引用
//json
{
"usingComponents": {
"tabbarCom":"/components/tabbarCom/tabbarCom"
}
}
//wxml 注意组件fixed要在组件外层套一个div否则添加内容会出现样式错位,fixed可以遮盖tabBar原有位置并且使原生tabBar无法背点击
<view style="position: fixed;bottom: 0;width: 100%;">
<tabbarCom tabs="{{tabs}}" bind:change="onTabItemChange" selected="{{selectedTab}}"></tabbarCom>
</view>
//js
Page({
data: {
tabs: [
{ icon: '/source/icon/homeN2x.png', selectedIcon: '/source/icon/home2x.png' ,pagePath: '/pages/index/index'},
{ icon: '/source/icon/createN2x.png',selectedIcon: '/source/icon/create2x.png' ,pagePath: '/pages/creativity/creativity'},
{ icon: '/source/icon/shopN2x.png',selectedIcon: '/source/icon/shop2x.png'',pagePath: '/pages/shopping/shopping' },
{ icon: '/source/icon/ucenterN2x.png',selectedIcon: '/source/icon/ucenter2x.png',pagePath: '/pages/ucenter/ucenter' }
],
selectedTab: 0
},
onTabItemChange: function(e) {
const index = e.detail.index;
// 判断当前选中状态是否已经改变
if (this.data.selectedTab !== index) {
this.setData({ selectedTab: index });
// 关闭当前所有页面并跳转到新的页面
console.log(index);
wx.switchTab({
url: this.data.tabs[index].pagePath,
})
}
},
onHide(){
this.setData({
selectedTab:0 //页面隐藏后要初始化,否则图片样式会保留在点击的图片样式上
})
},
onUnload(){
}
})
全局设置
//app.js
wx.hideTabBar() //隐藏微信自带的tabBar,只是css效果的隐藏
//app.json //一定要配置tabBar 否则wx.switchBar无法使用
"tabBar": {
"color": "#515151",
"selectedColor": "#6fe0ff",
"backgroundColor": "white",
"borderStyle": "white",
"list": [
{ "pagePath": "pages/index/index"},
{"pagePath": "pages/creativity/creativity"},
{"pagePath": "pages/shopping/shopping"},
{"pagePath": "pages/ucenter/ucenter"}
]