在做答题类的项目时,应该会比较常见多选题选相互斥的问题,例如:
你喜欢什么颜色?()
A、红色
B、紫色
C、蓝色
D、灰色
E、均无
如该题,当选择选项E时,明显与其他选项互斥。这个时候经常会出现勾选E后,A、B、C、D禁止选中的现象
以下为效果图:
具体思路如下:在遍历展示完数据之后,首先我们要给所有的选项增加一个是否禁止使用的标识。当用户点击选项时判断当前项是否与其他选项互斥,如果互斥,除选中项之外的其他选项禁止使用即可。
具体代码:
html:
<checkbox-group v-model="selectedItems" ref="checkboxGroup" @change="changeCheckbox">
<label class="options acea-row row-between row-middle" v-for="item in TestObject" :key="item.code">
<text>{{item.name}}</text>
<checkbox :value="item.code" :disabled="item.disabled" :checked="selectedItems.includes(item.code)"></checkbox>
</label>
</checkbox-group>
JS:
data:{
selectedItems:[],
TestObject: [
{ code: 'A', name: '红色', mutex: [] },
{ code: 'B', name: '紫色', mutex: [] },
{ code: 'C', name: '蓝色', mutex: [] },
{ code: 'D', name: '灰色', mutex: [] },
{ code: 'E', name: '均无', mutex: ['A','B','C','D'] }
]
}
....
changeCheckbox({detail}){
const {TestObject,selectedItems} = this;
const selectedValue = detail.value;
TestObject.forEach(item => {item.disabled = false });
selectedValue.forEach(value => {
const option = TestObject.find(opt => opt.code === value);
if (option && option.isMutex.length) {
option.isMutex.forEach(mutexCode => {
const mutexOption = TestObject.find(opt => opt.code === mutexCode);
if (mutexOption) {
mutexOption.disabled = true;
const index = selectedValue.indexOf(mutexCode);
if (index > -1) {
selectedValue.splice(index, 1);
}
}
});
}
});
this.$set(this, 'selectedItems', selectedValue);
}