首页 > 解决方案 > 当值相同的vuejs时,多个复选框不起作用

问题描述

当我检查苹果时,所有检查都是菠萝。当我取消选中 Pineapple 时,它​​也未选中 Apple。两个标签 ID 不同。我怎样才能只检查一个苹果而不是菠萝?

var demo = new Vue({
  el: '#demo',
  data: {
    checkedNames: []
  },
  computed: {
    computedNames() {
      let names = this.checkedNames;
      return names.toString();
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="demo">
  <input type="checkbox" id="50" value="50" v-model="checkedNames">
  <label for="Apple">Apple</label>
  <input type="checkbox" id="51" value="51" v-model="checkedNames">
  <label for="Banana">Banana</label>
  <input type="checkbox" id="52" value="50" v-model="checkedNames">
  <label for="Pineapple">Pineapple</label>
  <br>
  <span>Checked names: {{ checkedNames }}</span>
  <span>Computed names (reversed order): {{ computedNames }}</span>
</div>

标签: checkboxvuejs2

解决方案


Vue 是数据驱动的。由于您的ApplePineapple复选框具有相同的value,因此 Vue 认为它们是相同的。

听起来你想完全使用单独的对象,所以试试这个

var demo = new Vue({
  el: '#demo',
  data: () => ({
    options: [{
      id: 50,
      label: "Apple",
      price: 50
    }, {
      id: 51,
      label: "Banana",
      price: 51
    }, {
      id: 52,
      label: "Pineapple",
      price: 50
    }],
    selections: []
  }),
  computed: {
    computedNames: ({ selections }) =>
      selections.map(({ label }) => label).join(", ")
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="demo">
  <template v-for="fruit in options">
    <input
      :key="fruit.id"
      type="checkbox" 
      :value="fruit" 
      v-model="selections" 
      :id="`fruit_${fruit.id}`"
    >
    <label :for="`fruit_${fruit.id}`">{{ fruit.label }}</label>
  </template>
  <br>
  <span>Computed names: {{ computedNames }}</span>
  <pre>Selections: {{ selections }}</pre>
</div>


推荐阅读