給當前路由加上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>