vue实现多选互斥
实现多选互斥的逻辑
多选互斥指的是在多个选项中,允许选择多个,但某些选项之间存在互斥关系(即选择A会禁用B,反之亦然)。Vue中可以通过计算属性、watch或方法实现这一逻辑。
基础数据定义
在Vue组件的data或setup中定义选项列表和选中状态:

data() {
return {
options: [
{ id: 1, label: '选项A', group: 'group1' },
{ id: 2, label: '选项B', group: 'group1' },
{ id: 3, label: '选项C', group: 'group2' }
],
selected: []
}
}
互斥逻辑实现
通过计算属性或方法判断选项是否可选:
methods: {
isDisabled(option) {
const group = option.group;
return this.selected.some(item =>
item.group === group && item.id !== option.id
);
},
toggleSelection(option) {
if (this.isDisabled(option)) return;
const index = this.selected.findIndex(item => item.id === option.id);
if (index >= 0) {
this.selected.splice(index, 1);
} else {
this.selected.push(option);
}
}
}
模板渲染
在模板中使用v-for渲染选项,并绑定点击事件:

<template>
<div>
<div
v-for="option in options"
:key="option.id"
@click="toggleSelection(option)"
:class="{
'selected': selected.some(item => item.id === option.id),
'disabled': isDisabled(option)
}"
>
{{ option.label }}
</div>
</div>
</template>
样式控制
通过CSS增强交互反馈:
.selected {
background-color: #42b983;
color: white;
}
.disabled {
opacity: 0.5;
cursor: not-allowed;
}
组合式API实现(Vue 3)
使用Vue 3的setup语法:
import { ref } from 'vue';
export default {
setup() {
const selected = ref([]);
const options = ref([
{ id: 1, label: '选项A', group: 'group1' },
{ id: 2, label: '选项B', group: 'group1' },
{ id: 3, label: '选项C', group: 'group2' }
]);
const isDisabled = (option) => {
return selected.value.some(item =>
item.group === option.group && item.id !== option.id
);
};
const toggleSelection = (option) => {
if (isDisabled(option)) return;
const index = selected.value.findIndex(item => item.id === option.id);
if (index >= 0) {
selected.value.splice(index, 1);
} else {
selected.value.push(option);
}
};
return { options, selected, isDisabled, toggleSelection };
}
}






