vue实现跳转高亮
Vue 实现路由跳转高亮
在 Vue 中实现路由跳转高亮通常有两种常见方式:通过 router-link 的激活类或手动监听路由变化动态设置样式。
使用 router-link 的激活类
Vue Router 的 router-link 组件会自动为当前激活的路由链接添加特定类名(默认 router-link-active 或 router-link-exact-active),可直接利用这些类名设置高亮样式。
<template>
<router-link to="/home" class="nav-link">Home</router-link>
<router-link to="/about" class="nav-link">About</router-link>
</template>
<style>
.nav-link {
color: gray;
}
.nav-link.router-link-active {
color: red; /* 非精确匹配 */
}
.nav-link.router-link-exact-active {
color: blue; /* 精确匹配 */
}
</style>
动态绑定 class 或 style
通过计算属性或方法,根据当前路由动态绑定高亮样式。
<template>
<div
:class="{ active: $route.path === '/home' }"
@click="$router.push('/home')"
>Home</div>
<div
:class="{ active: $route.path === '/about' }"
@click="$router.push('/about')"
>About</div>
</template>
<style>
.active {
background-color: yellow;
}
</style>
使用 Vuex 或 Pinia 管理状态
对于复杂场景(如多层嵌套路由),可通过状态管理工具存储当前高亮项。
// Pinia 示例
import { defineStore } from 'pinia';
export const useNavStore = defineStore('nav', {
state: () => ({
activePath: '/'
})
});
<template>
<div
:class="{ active: activePath === '/home' }"
@click="setActive('/home')"
>Home</div>
</template>
<script setup>
import { useNavStore } from '@/stores/nav';
import { storeToRefs } from 'pinia';
const navStore = useNavStore();
const { activePath } = storeToRefs(navStore);
const setActive = (path) => {
navStore.activePath = path;
};
</script>
嵌套路由的高亮处理
嵌套路由需结合 route.matched 判断父级路径是否匹配。
computed: {
isActive() {
return this.$route.matched.some(record => record.path === this.to);
}
}
注意事项
- 精确匹配使用
router-link-exact-active,模糊匹配使用router-link-active。 - 动态绑定时注意响应式数据更新,避免直接修改
$route对象。 - 对于非
router-link元素,需手动监听路由变化(如使用watch或onBeforeRouteUpdate)。







