适用场景
首先我们要明白,为什么需要使用自定义tab栏
大家首先看一下uniapp关于原生tab跳转的api文档
https://uniapp.dcloud.net.cn/api/router.html#switchtab
大家可以清楚的看到,switchTab和navigateTo的差异为url后面是否可以携带参数
当我们在做一个简单的uniapp项目时,可能tab之间的切换,或者从其他页面前往tab页面的时候,不需要携带参数。但是,一旦我们需要携带参数跳转到tab页面的时候,原生的tab页面无法实现参数的携带。这个时候,我们就需要去构建一个通用的tab组件去实现它的跳转。并且,原生tab栏不支持你在上面做太多的样式拓展
缺点
在使用原生tab时,你会发现,tab之间的互相切换,并不会重新渲染页面。页面上的onload方法也不会再次被执行,切换的时候非常的丝滑。但如果你是用自定义tab栏时,你会发现,如果你使用navigateTo去完成tab页面的跳转,会造成页面栈的堆叠。
代码示例
<template>
<view class="tabbar">
<view class="tabbar-wraper">
<view class="tabbar-item" @tap="taberClick(0)">
<image class="icon" :style="{backgroundColor:navindex==0?globalStyle.mainColor:''}" src="" mode=""></image>
<view class="title" >首页</view>
</view>
<view class="tabbar-item" @tap="taberClick(1)">
<image class="icon" :style="{backgroundColor:navindex==1?globalStyle.mainColor:''}" src="" mode=""></image>
<view class="title">分类</view>
</view>
<view class="tabbar-item" @tap="taberClick(2)">
<image class="icon" :style="{backgroundColor:navindex==2?globalStyle.mainColor:''}" src="" mode=""></image>
<view class="title" >进货单</view>
</view>
<view class="tabbar-item" @tap="taberClick(3)">
<image class="icon" :style="{backgroundColor:navindex==3?globalStyle.mainColor:''}" src="" mode=""></image>
<view class="title">我的</view>
</view>
</view>
</view>
</template>
<script>
export default {
props: {
navindex: {
type: Number,
default: 0
}
},
data() {
return {
globalStyle: {
mainColor: 'red'
}
}
},
mounted() {
},
methods: {
taberClick(index) {
if(this.navindex == index){
return
}
console.log(index)
if(index == 0){
uni.redirectTo({
url: "../index/index"
})
return
}
if(index == 1){
uni.redirectTo({
url: "../tab1/tab1"
})
return
}
}
}
}
</script>
<style lang="scss" scoped>
.tabbar {
position: fixed;
left: 0;
right: 0;
bottom: 0;
z-index: 9;
background: #FFFFFF;
box-shadow: 0 0 5px rgba(0, 0, 0, .1);
.scan-img {
width: 80upx;
height: 80upx;
background-color: #333333;
border-radius: 80upx;
position: absolute;
top:-40upx;
left: 50%;
transform: translateX(-50%);
}
.tabbar-wraper {
display: flex;
justify-content: space-between;
align-items: center;
height: 100rpx;
}
.tabbar-item {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 90rpx;
width: 25%;
// width: 20%;
}
.icon {
width: 46rpx;
height: 46rpx;
}
.title {
text-align: center;
font-size: 20rpx;
color: #333333;
margin-top: 7rpx;
&.active {
color: #393939;
}
}
}
</style>