当前位置:首页 > VUE

vue实现多选互斥

2026-03-10 08:26:52VUE

实现多选互斥的逻辑

多选互斥指的是在多个选项中,允许选择多个,但某些选项之间存在互斥关系(即选择A会禁用B,反之亦然)。Vue中可以通过计算属性、watch或方法实现这一逻辑。

基础数据定义

在Vue组件的datasetup中定义选项列表和选中状态:

vue实现多选互斥

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渲染选项,并绑定点击事件:

vue实现多选互斥

<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 };
  }
}

标签: 多选互斥
分享给朋友:

相关文章

vue实现多选 全选

vue实现多选 全选

实现多选和全选功能 在Vue中实现多选和全选功能可以通过以下方式完成。假设有一个列表数据,需要实现勾选部分项或一键全选。 数据准备 定义一个数据列表和选中项的数组,以及全选状态。 data() {…

vue按钮实现多选

vue按钮实现多选

Vue 按钮实现多选的方法 在 Vue 中实现按钮多选功能,可以通过绑定 v-model 到数组或对象,结合样式控制来实现。以下是几种常见方法: 方法一:使用 v-model 绑定数组 通过将 v-…

vue实现单选多选

vue实现单选多选

Vue 实现单选功能 使用 v-model 绑定单选按钮的值,确保同一组单选按钮的 name 属性相同。 <template> <div> <lab…

vue实现多选列表

vue实现多选列表

Vue 实现多选列表的方法 使用 v-model 绑定数组 在 Vue 中,可以利用 v-model 指令绑定一个数组来实现多选功能。当用户选择多个选项时,选中的值会自动添加到数组中。 <te…

vue 实现按钮多选

vue 实现按钮多选

实现按钮多选功能 在Vue中实现按钮多选功能可以通过以下方法完成,主要依赖v-model绑定数组和v-for动态渲染按钮。 数据绑定与渲染 定义一个数组selectedItems用于存储选中的按钮值…

vue实现多选日历

vue实现多选日历

Vue 实现多选日历 使用 Vue 实现多选日历功能可以借助现有的日历库或手动构建。以下是两种常见方法: 使用第三方库(如 V-Calendar) 安装 V-Calendar 库: npm ins…