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

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

文章目录

本项目博客总结【前端】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>
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: vue