vue实现导航栏高亮
Vue 实现导航栏高亮的方法
动态绑定 class
通过 v-bind:class 或简写 :class 动态绑定高亮样式,结合当前路由或状态判断是否激活。
<template>
<nav>
<router-link
to="/home"
:class="{ 'active': $route.path === '/home' }"
>Home</router-link>
<router-link
to="/about"
:class="{ 'active': $route.path === '/about' }"
>About</router-link>
</nav>
</template>
<style>
.active {
color: #42b983;
font-weight: bold;
}
</style>
使用 Vue Router 的 exact-active-class
Vue Router 内置 exact-active-class 属性,可自动匹配精确路由。
<router-link
to="/home"
exact-active-class="active"
>Home</router-link>
计算属性判断
通过计算属性返回高亮状态,适用于复杂条件。
<template>
<nav>
<a @click="navigate('/home')" :class="{ active: isActive('/home') }">Home</a>
<a @click="navigate('/about')" :class="{ active: isActive('/about') }">About</a>
</nav>
</template>
<script>
export default {
methods: {
navigate(path) {
this.$router.push(path);
},
isActive(path) {
return this.$route.path === path;
}
}
};
</script>
使用 CSS 伪类
结合 Vue Router 的 router-link 和 CSS 伪类实现高亮。
<router-link to="/home" class="nav-link">Home</router-link>
<router-link to="/about" class="nav-link">About</router-link>
<style>
.router-link-exact-active.nav-link {
color: #42b983;
border-bottom: 2px solid #42b983;
}
</style>
嵌套路由高亮
处理嵌套路由时,使用 $route.matched 检查路径层级。
<template>
<a :class="{ active: isActive('/products') }">Products</a>
</template>
<script>
export default {
methods: {
isActive(path) {
return this.$route.matched.some(route => route.path === path);
}
}
};
</script>
注意事项
- 动态绑定
class时,确保样式优先级足够覆盖默认样式。 - 使用
exact-active-class时,若需模糊匹配(如子路由),改用active-class。 - 对于非路由导航,可通过状态管理(如 Vuex)存储当前激活项。







