仅选中一个复选框后,如何禁用复选框选项?

How to make a checkbox option disabled once only a single checkbox is checked?

问题:

我有 2 个复选框 - 考虑选项 A 和选项 B

至少应选中其中一项,因此如果未选中其中一项,则应禁用另一项。如果两者都被选中,则两者都不应被禁用。总之,一定不能是两者都可以取消勾选的情况。

我正在使用 vue-bootstrap 复选框组件,它有一个禁用的 属性,但我无法根据我的情况使其动态化。这是代码:

<b-form-checkbox-group v-model="selectedFruit" @change="changeFruits">
  <b-form-checkbox v-for="fruit in availableFruits" :key="fruit.id" :value="fruit.name" :disabled="checkifDisabled">
    {{ fruit.name }}
  </b-form-checkbox>
</b-form-checkbox-group>

我正在尝试使用 vue computed 属性 来执行此操作,但没有在 computed 属性.

中准确定位目标
selectedFruit: [],

availableFruits: [
    {
      id: 1,
      name: 'Apple',
    },
    {
      id: 2,
      name: 'Mango',
    }
],

computed: {
  checkifDisabled: function() {
      /// Need to do something here to achieve this
      return true
  }
},

定义一个附加属性以在 v-model 中使用,并在复选框标记中添加以下内容 属性,同时删除 :value 部分,因为它不再需要

<b-form-checkbox-group v-model="selectedFruit" @change="changeFruits">
  <b-form-checkbox v-for="(fruit, index) in availableLaws" :key="fruit.id" v-model="fruit.pick" value="picked"
      unchecked-value="not_picked" :disabled="fruit.pick === 'picked'">
    {{ fruit.name }}
  </b-form-checkbox>
</b-form-checkbox-group>

你的数据就像

data() {
 return {
  selectedLaws: [],

  availableLaws: [
    {
      id: 1,
      name: 'Apple',
      pick: 'not_picked' // new change
    },
    {
      id: 2,
      name: 'Mango',
      pick: 'not_picked' //// new change
    }
 ],
};
}

此处无需使用计算属性

您可以将一个方法绑定到 disabled,它检查复选框是否应该被禁用。 在您的情况下,您想检查所选数组中是否只有一项,并禁用数组中包含哪个值的复选框。

new Vue({
  el: '#app',
  data() {
    return {
      selectedFruit: [],
      availableFruits: [{
          id: 1,
          name: 'Banana'
        },
        {
          id: 2,
          name: 'Strawberry'
        },
        {
          id: 3,
          name: 'Cherry'
        },
        {
          id: 4,
          name: 'Apple'
        }
      ]
    }
  },
  methods: {
    isDisabled(fruit) {
      const {
        selectedFruit
      } = this
      return selectedFruit.length === 1 && selectedFruit[0] === fruit.name
    }
  }
})
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.css" />
<script src="https://unpkg.com/vue@2.6.2/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>

<div id="app" class="p-2">
  <b-form-checkbox-group v-model="selectedFruit">
    <b-form-checkbox v-for="fruit in availableFruits" :key="fruit.id" :value="fruit.name" :disabled="isDisabled(fruit)">
      {{ fruit.name }}
    </b-form-checkbox>
  </b-form-checkbox-group>
</div>