vue实现排他思想
排他思想在 Vue 中的实现
在 Vue 中实现排他思想(即多个元素中只能有一个处于激活状态)可以通过以下方法实现:
方法一:使用 v-model 绑定同一变量

<template>
<div>
<button
v-for="item in items"
:key="item.id"
@click="activeItem = item.id"
:class="{ active: activeItem === item.id }"
>
{{ item.text }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
activeItem: null,
items: [
{ id: 1, text: '选项1' },
{ id: 2, text: '选项2' },
{ id: 3, text: '选项3' }
]
}
}
}
</script>
方法二:使用计算属性和方法

<template>
<div>
<button
v-for="item in items"
:key="item.id"
@click="setActive(item.id)"
:class="{ active: isActive(item.id) }"
>
{{ item.text }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
activeItem: null,
items: [
{ id: 1, text: '选项1' },
{ id: 2, text: '选项2' },
{ id: 3, text: '选项3' }
]
}
},
methods: {
setActive(id) {
this.activeItem = id
},
isActive(id) {
return this.activeItem === id
}
}
}
</script>
方法三:使用组件间通信(父子组件)
<!-- 父组件 -->
<template>
<div>
<ChildComponent
v-for="item in items"
:key="item.id"
:item="item"
:active="activeItem === item.id"
@activate="activeItem = $event"
/>
</div>
</template>
<!-- 子组件 -->
<template>
<button
@click="$emit('activate', item.id)"
:class="{ active: active }"
>
{{ item.text }}
</button>
</template>
方法四:使用 Vuex 管理状态(适用于复杂应用)
// store.js
export default new Vuex.Store({
state: {
activeItem: null
},
mutations: {
setActive(state, id) {
state.activeItem = id
}
}
})
// 组件中使用
<template>
<button
@click="$store.commit('setActive', item.id)"
:class="{ active: $store.state.activeItem === item.id }"
>
{{ item.text }}
</button>
</template>
实现要点
- 维护一个存储当前激活项的变量(如
activeItem) - 通过点击事件更新该变量
- 根据该变量与当前项的比较结果来应用样式或状态
- 对于列表项,通常结合
v-for指令实现
样式处理示例
.active {
background-color: #42b983;
color: white;
}
这些方法可以根据具体场景选择使用,简单场景推荐前两种方法,复杂应用可考虑使用Vuex管理状态。






