【前端】Vue项目:旅游App-(18)TabBar:debug,非点击tabBar的路由跳转active显示问题

文章讲述了在Vue项目中,针对旅游App的tabBar在路由跳转时不更新的问题进行的修复。通过添加vant组件的route和replace属性,以及监听路由变化更新currentIndex,成功解决了tabBar未正确反映当前活跃页面的状态。
摘要由CSDN通过智能技术生成

本项目博客总结:【前端】Vue项目:旅游App-博客总结

目标

当我们在url处实现路由跳转时,tabBar没有产生对应的修改。

在这里插入图片描述
我们要消除这个bug。

过程与代码

原因与属性的添加

分析一下原因,实现路由跳转有两种方式:

  • url的修改
  • 在tabBar的点击跳转

我们这里的tabBar用的是vant库,所以先看看文档有没有对应的说明:Tabbar 标签栏 - Vant 4 (gitee.io)

在这里插入图片描述
这两个属性的具体含义在文档中也有写:

  • route:是否开启路由模式,默认为false
  • replace:是否在跳转时替换当前页面历史,默认为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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

karshey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值