1.点击进入二级路由后,回到一级时,tab栏的高亮会默认跳到第一个(见图2),而不是高亮当前的页面
在项目过程中遇到的,希望能为大家解决问题,谢谢!
正确的案例:
err的案例:
2.vue2用vant页面显示的代码(layout的4个tab按钮):
这里用的icon是云上的,需要引入,复制无效果
<template>
<div class="box">
<router-view></router-view>
<!-- tab -->
<van-tabbar v-model="active" :safe-area-inset-bottom="false" inactive-color="#333" active-color="#415afc">
<van-tabbar-item badge="" to="/">
<span>首页</span>
<template #icon="props">
<i :class="['iconfont',`${props.active ? 'icon-shouyefill':'icon-shouye'}`]"></i>
</template>
</van-tabbar-item>
<van-tabbar-item badge="" to="/classify">
<span>分类</span>
<template #icon="props">
<i :class="['iconfont',`${props.active ? 'icon-classify-select':'icon-classfig-un'}`]"></i>
</template>
</van-tabbar-item>
<van-tabbar-item badge="" to="/shopping">
<span>购物车</span>
<template #icon="props">
<i :class="['iconfont',`${props.active ? 'icon-cart-select':'icon-gouwuche'}`]"></i>
</template>
</van-tabbar-item>
<van-tabbar-item badge="" to="/my">
<span>我的</span>
<template #icon="props">
<i :class="['iconfont',`${props.active ? 'icon-mine-select':'icon-mine-unselect'}`]"></i>
</template>
</van-tabbar-item>
</van-tabbar>
</div>
</template>
<script>
export default {
data() {
return {
active: 0, // 让底部高亮
}
},
}
</script>
<style lang="scss" scoped>
.box {
height:100%;
background-color: #fafafa;
}
::v-deep .van-tabbar {
height:60px;
padding-bottom:20px;
z-index: 999;
}
::v-deep .van-tabbar-item__icon img{
height:24px;
width:27px;
object-fit:contain;
//控制图片如何在 img 元素里显示
}
::v-deep .van-tabbar-item__text{
font-weight:bold;
}
</style>
3.解决方案:
1.运用侦听器监听路由变化
watch: {
$route: function(newV) {
if (newV.path == '/' || newV.path == '/home') {
this.active = 0;
} else if (newV.path == '/classify') {
this.active = 1;
} else if (newV.path == '/shopping') {
this.active = 2;
} else if (newV.path == '/my') {
this.active = 3;
}
}
},
2.钩子函数强制控制
mounted() {
if (this.$route.path == '/' || this.$route.path == '/home') {
this.active = 0;
} else if (this.$route.path == '/classify') {
this.active = 1;
} else if (this.$route.path == '/shopping') {
this.active = 2;
} else if (this.$route.path == '/my') {
this.active = 3;
}
}
4.解决完毕
如有更好的方案或解决方法可以说出来哦,谢谢,若有错误,请指正!