vue实现跳转高亮
Vue 实现路由跳转高亮
在 Vue 中实现路由跳转时的高亮效果,通常需要结合 vue-router 和 CSS 样式来完成。以下是几种常见的方法:
使用 router-link-active 类
vue-router 会自动为当前活跃的路由链接添加 router-link-active 类。可以利用这个类来设置高亮样式。
<template>
<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>
</template>
<style>
.router-link-active {
color: red;
font-weight: bold;
}
</style>
自定义高亮类名
如果希望使用自定义的类名,可以通过 vue-router 的配置来实现。
const router = new VueRouter({
routes,
linkActiveClass: 'custom-active-class'
});
<style>
.custom-active-class {
color: blue;
text-decoration: underline;
}
</style>
动态绑定样式
对于更复杂的高亮需求,可以使用动态绑定类名或样式的方式。
<template>
<router-link
to="/home"
:class="{ 'active': $route.path === '/home' }"
>Home</router-link>
<router-link
to="/about"
:class="{ 'active': $route.path === '/about' }"
>About</router-link>
</template>
<style>
.active {
background-color: yellow;
}
</style>
嵌套路由的高亮
对于嵌套路由,可以使用 router-link-exact-active 类来精确匹配当前路由。
<style>
.router-link-exact-active {
border-bottom: 2px solid green;
}
</style>
使用导航守卫
如果需要在高亮时执行一些逻辑,可以使用导航守卫。

router.beforeEach((to, from, next) => {
console.log(`Navigating to ${to.path}`);
next();
});
以上方法可以根据具体需求选择使用,灵活组合以实现最佳的高亮效果。






