当前位置:首页 > 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 实现级联多选的方法 使用 Element UI 的 Cascader 组件 Element UI 提供了 el-cascader 组件,支持多选功能。通过设置 props 的 multiple…

vue循环实现多选

vue循环实现多选

Vue循环实现多选的方法 在Vue中实现多选功能,可以通过v-for循环渲染选项,结合v-model绑定数组来记录选中的值。以下是具体实现方式: 基础实现方案 数据准备 在组件的data中定义选项…

vue实现li多选

vue实现li多选

Vue 实现列表多选功能 在 Vue 中实现列表(<li>)的多选功能可以通过多种方式完成。以下是几种常见的实现方法: 使用 v-model 绑定数组 通过 v-model 绑定一个数组…

js 多选 实现

js 多选 实现

实现多选的 JavaScript 方法 使用复选框(Checkbox)实现多选 通过 HTML 的 checkbox 元素配合 JavaScript 实现多选功能。用户可以选择多个选项,提交时获取所有…

vue点击实现多选

vue点击实现多选

Vue 实现多选功能的方法 在 Vue 中实现多选功能可以通过多种方式完成,以下介绍几种常见的实现方法: 使用 v-model 绑定数组 通过 v-model 绑定一个数组,当复选框被选中时,会自动…

vue实现tab多选

vue实现tab多选

Vue 实现 Tab 多选功能 在 Vue 中实现 Tab 多选功能可以通过以下方法完成。假设需要实现一个可多选的 Tab 组件,用户可以通过点击 Tab 来选择多个选项。 数据结构和状态管理 定义…