vue实现跳转高亮
Vue 实现跳转高亮的方法
使用 router-link 和 active-class
在 Vue Router 中,router-link 组件会自动为当前激活的路由链接添加一个 router-link-active 类。可以通过 active-class 属性自定义类名。
<router-link to="/home" active-class="active">Home</router-link>
<router-link to="/about" active-class="active">About</router-link>
.active {
color: #42b983;
font-weight: bold;
}
动态绑定 class 或 style
通过判断当前路由路径,动态绑定 class 或 style 实现高亮效果。
<template>
<div>
<a
href="#"
:class="{ active: $route.path === '/home' }"
@click="$router.push('/home')"
>Home</a>
<a
href="#"
:class="{ active: $route.path === '/about' }"
@click="$router.push('/about')"
>About</a>
</div>
</template>
.active {
color: #42b983;
font-weight: bold;
}
使用 watch 监听路由变化
在组件中监听路由变化,动态设置高亮状态。
<template>
<div>
<a
href="#"
:class="{ active: activeTab === 'home' }"
@click="navigateTo('home')"
>Home</a>
<a
href="#"
:class="{ active: activeTab === 'about' }"
@click="navigateTo('about')"
>About</a>
</div>
</template>
<script>
export default {
data() {
return {
activeTab: 'home'
}
},
watch: {
'$route.path'(newPath) {
this.activeTab = newPath === '/home' ? 'home' : 'about'
}
},
methods: {
navigateTo(tab) {
this.activeTab = tab
this.$router.push(`/${tab}`)
}
}
}
</script>
使用 Vuex 管理高亮状态
对于复杂应用,可以使用 Vuex 统一管理高亮状态。
// store.js
export default new Vuex.Store({
state: {
activeTab: 'home'
},
mutations: {
setActiveTab(state, tab) {
state.activeTab = tab
}
}
})
<template>
<div>
<a
href="#"
:class="{ active: $store.state.activeTab === 'home' }"
@click="navigateTo('home')"
>Home</a>
<a
href="#"
:class="{ active: $store.state.activeTab === 'about' }"
@click="navigateTo('about')"
>About</a>
</div>
</template>
<script>
export default {
methods: {
navigateTo(tab) {
this.$store.commit('setActiveTab', tab)
this.$router.push(`/${tab}`)
}
}
}
</script>
结合 scrollBehavior 实现滚动高亮
在路由配置中设置 scrollBehavior,结合 IntersectionObserver 实现滚动高亮。

// router.js
const router = new VueRouter({
routes: [...],
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return {
selector: to.hash,
behavior: 'smooth'
}
}
}
})
<template>
<div>
<a href="#section1" :class="{ active: activeSection === 'section1' }">Section 1</a>
<a href="#section2" :class="{ active: activeSection === 'section2' }">Section 2</a>
</div>
</template>
<script>
export default {
data() {
return {
activeSection: 'section1'
}
},
mounted() {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.activeSection = entry.target.id
}
})
}, { threshold: 0.5 })
document.querySelectorAll('section').forEach(section => {
observer.observe(section)
})
}
}
</script>






