You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vuetify v-select多选时按类型互斥禁用选项的实现需求

刚好做过类似的需求,我来给你整理一下实现方案!核心就是通过监听选中项的变化,动态切换不同类型食谱的禁用状态,具体代码和解释如下:

实现Vuetify v-select多选时的类型互斥禁用功能

你需要的是在开启multiple的v-select组件中,实现“选了晚餐类食谱就禁用所有早餐选项,选了早餐就禁用所有晚餐选项”的互斥逻辑,下面是完整的实现方案:

完整代码示例

HTML模板

<div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <v-row align="center">
        <v-col cols="12" sm="4">
          <v-subheader v-text="'You can only select one type'"></v-subheader>
        </v-col>
        <v-col cols="12" sm="2">
          <v-select
            v-model="selected"
            :items="recipes"
            label="Select"
            multiple
            hint="Pick your meal"
            persistent-hint
            item-value="id"
            item-text="name"
          ></v-select>
        </v-col>
      </v-row>
      Selected: {{ selected }}<br>
      Recipes: {{ recipes }}
    </v-container>
  </v-app>
</div>

JavaScript逻辑

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      selected: [],
      recipes: [
        { 'id': 1, 'name': 'Pizza', 'type': 'Dinner', 'disabled': false },
        { 'id': 2, 'name': 'Omelet', 'type': 'Breakfast', 'disabled': false },
        { 'id': 3, 'name': 'Scrambled Eggs', 'type': 'Breakfast', 'disabled': false },
      ],
    }
  },
  watch: {
    selected(newVal) {
      // 如果没有选中项,恢复所有食谱可用
      if (newVal.length === 0) {
        this.recipes.forEach(recipe => {
          recipe.disabled = false;
        });
        return;
      }

      // 获取当前选中项对应的类型集合(去重)
      const selectedTypes = [...new Set(
        this.recipes.filter(r => newVal.includes(r.id)).map(r => r.type)
      )];

      // 如果选中了晚餐类型,禁用所有早餐;反之禁用晚餐
      if (selectedTypes.includes('Dinner')) {
        this.recipes.forEach(recipe => {
          recipe.disabled = recipe.type === 'Breakfast';
        });
      } else if (selectedTypes.includes('Breakfast')) {
        this.recipes.forEach(recipe => {
          recipe.disabled = recipe.type === 'Dinner';
        });
      }
    }
  }
})

关键逻辑解释

  • 监听选中项变化:通过Vue的watch监听selected数组,每次选中项更新时触发逻辑
  • 类型判断:先通过选中的ID找到对应的食谱,提取它们的类型并去重,确定当前选中的类型
  • 动态设置禁用状态:根据选中的类型,遍历食谱数组,把对立类型的食谱设置为disabled: true,选中类型的保持可用;如果清空选中项,就恢复所有食谱的可用状态

这样就能完美实现你要的互斥禁用效果啦!

内容的提问来源于stack exchange,提问作者5less

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 13:47:43