1.新建custom-tab-bar目录 ,并分别创建 (js,json,wxml,wxss)
index.json
{
"component": true
}
index.wxml
<view class="tab-bar">
<view wx:for="{{list}}" wx:key="index" class="tab-bar-item {{item.diyClass}}" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
<image src="{{selected === index ? item.selectedIconPath : item.iconPath}}" class="{{item.diyClass}}" mode="aspectFit"/>
<view style="color: {{selected === index ? selectedColor : color}}" class="{{item.diyClass}}">{{item.text}}</view>
</view>
</view>
index.wxss
/*重新样式*/
.tab-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
box-shadow: 0px -2px 10px 0px rgba(0,0,0,0.05);
box-sizing: content-box;
}
.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: auto;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
background: #fff;
height: 120rpx;
}
.tab-bar-item.diy {
margin-top: 0!important;
background: transparent;
position: relative;
flex: inherit;
width: 134rpx;
}
.tab-bar-item image {
width: 48rpx;
height: 48rpx;
overflow: initial;
}
.tab-bar-item view {
font-size: 24rpx;
}
.tab-bar-item image.diy {
position: absolute;
width: 134rpx;
height: 140rpx;
bottom: 25.6%;
z-index: 100;
}
.tab-bar-item view.diy {
margin-top: 90rpx;
background: #fff;
width: 100%;
height: 100%;
padding-top: 58rpx;
z-index: 99;
}
index.js
const app = getApp()
Component({
data: {
selected: 0, //当前选中的tab下标
color: "#1E1E1E",
selectedColor: "#2B71F2", //tabbar选中字体颜色
list: [{
pagePath: "pages/home/index",
text: "首页",
iconPath: "/static/home.png",
selectedIconPath: "/static/home_active.png"
},
{
pagePath: "pages/home/popularScience",
text: "科普",
iconPath: "/static/popularScience.png",
selectedIconPath: "/static/popularScience_active.png"
},
{
pagePath: "pages/home/report",
text: "报告",
iconPath: "/static/report.png",
selectedIconPath: "/static/report.png"
},
{
pagePath: "pages/home/ai",
text: "AI检测",
iconPath: "/static/ai.png",
selectedIconPath: "/static/ai_active.png"
},
{
pagePath: "pages/mine/index",
text: "我的",
iconPath: "/static/mine.png",
selectedIconPath: "/static/mine_active.png"
}
], //tabbar循环数据集
},
attached() {},
methods: {
switchTab(e) {
console.log(e)
const data = e.currentTarget.dataset;
const url = data.path
this.setData({
selected: data.index
})
wx.switchTab({
url: "/" + url
})
},
},
})
main.js中添加,解决点击两次才能选择icon
Vue.mixin({
methods:{
setTabBarIndex(index) {
if (typeof this.$mp.page.getTabBar === 'function' &&
this.$mp.page.getTabBar()) {
this.$mp.page.getTabBar().setData({
selected: index
})
}
}
}
})
在当前页下,onShow中添加
onShow() {
if (typeof this.$mp.page.getTabBar === 'function' &&
this.$mp.page.getTabBar()) {
this.$mp.page.getTabBar().setData({
selected: 0
})
}
}