vue如何实现菜单高亮
Vue实现菜单高亮的方法
动态绑定class或style
通过v-bind:class或v-bind:style动态绑定高亮样式。根据当前路由或状态判断是否激活菜单项,添加高亮类名或样式。
<template>
<div>
<router-link
to="/home"
:class="{ 'active': $route.path === '/home' }">
首页
</router-link>
<router-link
to="/about"
:class="{ 'active': $route.path === '/about' }">
关于
</router-link>
</div>
</template>
<style>
.active {
color: red;
font-weight: bold;
}
</style>
使用Vue Router的exact-active-class
Vue Router提供exact-active-class属性,自动为匹配当前路由的导航项添加高亮类名,无需手动判断。

<router-link
to="/home"
exact-active-class="active">
首页
</router-link>
通过计算属性管理高亮状态
对于复杂逻辑,可使用计算属性返回高亮类名或样式对象,集中管理高亮条件。

<template>
<div :class="menuClass">菜单项</div>
</template>
<script>
export default {
computed: {
menuClass() {
return {
active: this.$route.path === '/home',
'has-notification': this.hasNotification
};
}
}
};
</script>
嵌套菜单的高亮处理
对于嵌套菜单,可通过递归组件或遍历路由表实现子菜单高亮,结合$route.matched判断路由层级匹配。
// 示例:检查路由是否匹配
isActive(routePath) {
return this.$route.matched.some(route => route.path === routePath);
}
第三方库辅助
使用vue-router-active-path等库简化高亮逻辑,适用于动态路由或复杂匹配场景。
import { isActivePath } from 'vue-router-active-path';
// 在模板或方法中调用
isActivePath('/dynamic-route');






