本项目博客总结:【前端】Vue项目:旅游App-博客总结
目标
当我们在url处实现路由跳转时,tabBar没有产生对应的修改。
我们要消除这个bug。
过程与代码
原因与属性的添加
分析一下原因,实现路由跳转有两种方式:
- url的修改
- 在tabBar的点击跳转
我们这里的tabBar用的是vant库,所以先看看文档有没有对应的说明:Tabbar 标签栏 - Vant 4 (gitee.io)
这两个属性的具体含义在文档中也有写:
route
:是否开启路由模式,默认为falsereplace
:是否在跳转时替换当前页面历史,默认为false
我们把这两个属性添加上。
效果:
实现了但没完全实现。
currentIndex的修改
出现上图的问题的原因是:我们的active分为两部分显示,对应图片部分没有完成
- 图片:active后根据
currentIndex
修改图片,此部分没有完成 - 文字:active后直接变颜色(
--primary-color
),此部分已完成
观察代码,不难发现,在改变url时我们是没有改变currentIndex
的,想要修改这个错误,我们就需要在改变url是把currentIndex
对应地修改过来。
如何修改呢?监听路由的改变即可。
注意:path不在tabBar中的情况(如city),没找到要返回-1
const currentIndex = ref(0)
const route = useRoute()
watch(route, (newRoute) => {
const index = tabbarData.findIndex(item => item.path === newRoute.path)
// path不在tabBar的情况,如city
if (index === -1) return
currentIndex.value = index
})
效果
总代码
修改的文件:tab-bar.vue
<!-- 用Vant库的代码 -->
<template>
<!-- 双向绑定currentIndex,则不用监听点击 -->
<van-tabbar route v-model="currentIndex" active-color=var(--primary-color)>
<van-tabbar-item repalce v-for="(item, index) in tabbarData" :to="item.path">
<span>{{ item.text }}</span>
<template #icon>
<img :src="currentIndex === index ? getAssetsUrl(item.imageActive) : getAssetsUrl(item.image)" />
</template>
</van-tabbar-item>
</van-tabbar>
</template>
<script setup>
import tabbarData from '@/assets/data/tabbarData'
import { getAssetsUrl } from '@/utils/load_assets'
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
const currentIndex = ref(0)
const route = useRoute()
watch(route, (newRoute) => {
const index = tabbarData.findIndex(item => item.path === newRoute.path)
// path不在tabBar的情况,如city
if (index === -1) return
currentIndex.value = index
})
</script>
<style lang="less" scoped>
:deep(.van-tabbar-item) {
height: 50px;
img {
height: 30px;
}
}
</style>