vue从地址栏输入路径后path和导航按钮不匹配问题

问题描述:从url直接输入某个页面的路径后,导航按钮并不会对应的出现高亮。

 

来看看,先前我是如何做active样式的:

高亮是通过.router-link-active实现的,这个是没有bug:

 .router-link-active .tabbar_text {
    color: var(--primary-color);
  }

active图片是通过监听点击,传入当前页面对应的索引,v-if当前索引比对自身索引来实现的:

<div class="tabbar_wrap">
      <template v-for="(data, index) in tabbarData" :key="data.id">
        <router-link :to="data.path" @click="handleClikLink(index)">
          <img
            :src="getAssetURl(data.image)"
            :alt="data.text"
            v-if="$route.meta.currentIndex !== index"
          />
          <img :src="getAssetURl(data.imageActive)" :alt="data.text" v-else />
          <span class="tabbar_text">{{ data.text }}</span>
        </router-link>
      </template>
    </div>
​
​
//set up
const currentIndex = ref(0);
const handleClikLink = (index) => {
  currentIndex.value = index;
};

问题的根源:是因为当前索引默认是0的,而切换当前索引需要点击对应的router-link,但是我们直接通过path切换是不会触发点击事件的,这就导致页面切换了,但是按钮没变的尴尬事件。

解决方法:

方案1:给路由对象添加meta属性,用于保存当前索引,组件中用v-if比对 当前路由对象中保存的当前索引和自身索引,从而实现active样式。

  //这里只演示了一个route
   {
      path: "/home",
      component: () => import("../views/home/Home.vue"),
      meta: {
        currentIndex: 0,
      },
    },
//需要切换的元素或组件中加入v-if
v-if="$route.meta.currentIndex !== index"

如果不喜欢在template中写这么长的的表达式,页可以在组合式api也就是setup中调用useRoute(),返回当前路由对象。相当于在模板中使用 $route。然后再用个computed或者watch都行。

方案2:用watch的话就可以监听改变,然后改ref的值。这里监不听监听都可以。

const currentIndex = ref(0);
const handleClikLink = (index) => {
  currentIndex.value = index;
};
const route = useRoute();
watch(route, (newValue) => {
  currentIndex.value = newValue.meta.currentIndex;
});

方案3:用computed的话就返回一个不可变的响应式ref对象,根据这个ref的值再去比较自身索引即可。

const route = useRoute();
const currentIndex = computed(() => {
  return route.meta.currentIndex;
});

当然我还是喜欢直接在template中用$route,简单粗暴。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值