vue实现active
实现 Vue 中的 active 状态
在 Vue 中实现 active 状态通常用于高亮当前选中的元素,比如导航菜单、按钮或列表项。可以通过以下几种方式实现:
使用 v-bind:class
通过动态绑定 class 来实现 active 状态,根据条件添加或移除 active 类名。

<template>
<button
v-for="item in items"
:key="item.id"
@click="activeItem = item.id"
:class="{ active: activeItem === item.id }"
>
{{ item.text }}
</button>
</template>
<script>
export default {
data() {
return {
activeItem: null,
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
]
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用 Vue Router 的 active 类
如果是在路由导航中使用 active 状态,可以利用 Vue Router 自带的 router-link-active 和 router-link-exact-active 类。

<template>
<router-link to="/home" active-class="active">Home</router-link>
<router-link to="/about" active-class="active">About</router-link>
</template>
<style>
.active {
font-weight: bold;
color: #42b983;
}
</style>
使用计算属性
对于更复杂的 active 状态逻辑,可以使用计算属性来动态生成 class 或 style。
<template>
<div
v-for="tab in tabs"
:key="tab.id"
@click="currentTab = tab.id"
:class="tabClass(tab.id)"
>
{{ tab.name }}
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 'home',
tabs: [
{ id: 'home', name: 'Home' },
{ id: 'about', name: 'About' }
]
}
},
methods: {
tabClass(tabId) {
return {
'tab-item': true,
'active': this.currentTab === tabId
}
}
}
}
</script>
使用 CSS 伪类
对于简单的交互效果,可以直接使用 CSS 伪类如 :active 来实现点击时的瞬时 active 状态。
<template>
<button class="btn">Click Me</button>
</template>
<style>
.btn:active {
transform: scale(0.98);
background-color: #e0e0e0;
}
</style>
以上方法可以根据具体需求选择使用,通常动态 class 绑定是最常用的方式,特别是在需要持久 active 状态的场景中。






