vue路由精确匹配模式 exact

时间:2021-08-06
本文章向大家介绍vue路由精确匹配模式 exact,主要包括vue路由精确匹配模式 exact使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

给当前路由加上active类名高亮显示:

<template>
  <div id="app">
    <router-link to='/' active-class="active">首页</router-link> |
    <router-link :to="{name:'about'}" active-class="active">关于</router-link>
    <router-view></router-view>
  </div>
</template>
.active{
  color: greenyellow;
}

此时,点击“关于”时两个都高亮了

原因是默认情况下路由是包含匹配模式,也就是 / 和 /about 都是 / 开头,以 / 开头的路由都会被匹配上active类名

解决:

1、给 / 路由加上exact属性,/ 就变成了精确匹配模式,必须是 / 才会匹配过来,/about不会匹配过来

<template>
  <div id="app">
    <router-link to='/' active-class="active" exact>首页</router-link> |
    <router-link :to="{name:'about'}" active-class="active">关于</router-link>
    <router-view></router-view>
  </div>
</template>

2、补全 / 的路径(/home)

<template>
  <div id="app">
    <router-link to='/home' active-class="active">首页</router-link> |
    <router-link :to="{name:'about'}" active-class="active">关于</router-link>
    <router-view></router-view>
  </div>
</template>

原文地址:https://www.cnblogs.com/wuqilang/p/15110327.html