vue实现排他思想
排他思想的概念
排他思想指在交互中,确保同一时间只有一个元素处于激活状态(如选项卡、菜单项等)。Vue 中可通过数据驱动和事件绑定实现这一逻辑。

方法一:使用 v-for 和动态类名
通过遍历数组生成元素,利用当前选中索引控制激活状态。

<template>
<div>
<button
v-for="(item, index) in items"
:key="index"
@click="activeIndex = index"
:class="{ 'active': activeIndex === index }"
>
{{ item }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
items: ['选项1', '选项2', '选项3'],
activeIndex: 0 // 默认选中第一个
};
}
};
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
方法二:使用计算属性
通过计算属性动态判断当前激活项,适合复杂逻辑。
<template>
<div>
<button
v-for="(item, index) in items"
:key="index"
@click="setActive(index)"
:class="isActive(index)"
>
{{ item }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
items: ['选项A', '选项B', '选项C'],
activeIndex: null // 初始无选中
};
},
methods: {
setActive(index) {
this.activeIndex = index;
}
},
computed: {
isActive() {
return (index) => ({ active: this.activeIndex === index });
}
}
};
</script>
方法三:组件化封装
将排他逻辑封装为可复用组件,通过 v-model 或 props 控制状态。
<!-- ExclusiveButtons.vue -->
<template>
<div>
<button
v-for="(item, index) in options"
:key="index"
@click="$emit('update:modelValue', index)"
:class="{ 'active': modelValue === index }"
>
{{ item }}
</button>
</div>
</template>
<script>
export default {
props: {
options: { type: Array, required: true },
modelValue: { type: Number, default: 0 }
}
};
</script>
<!-- 父组件使用 -->
<template>
<ExclusiveButtons
v-model="selectedIndex"
:options="['Tab1', 'Tab2', 'Tab3']"
/>
</template>
注意事项
- 唯一标识:确保
v-for的:key使用唯一值(如id而非索引)。 - 初始状态:明确初始化
activeIndex避免未选中状态。 - 样式隔离:通过
scoped样式防止类名冲突。
通过以上方法,可灵活实现 Vue 中的排他交互逻辑。






