@click on复选框添加/删除数据

时间:2017-10-06 18:56:03

标签: javascript vue.js vuejs2

我目前有以下情况:

我有多个复选框,一旦点击任何一个复选框,它的值将被添加到一个数组中。如果未选中该复选框,则需要再次从该数组中删除该项目。

selectAddOn(addOnId) {
    if (! this.selectedAddOns.includes(addOnId)) {
        this.selectedAddOns.push(addOnId);
    }
}

以下作品并将其添加到我的selectedAddOns[]。但是,再次选中该复选框时,不会删除该复选框。当然,我可以使用else,但是......

不幸的是,浏览器的行为是当你点击<label>时,会在<input>上自动触发点击事件,因此外部div接收2个事件,一个来自标签,一个来自输入。我知道我可以通过在@click.prevent上添加<label>来解决此问题,但这不会添加我的自定义复选框样式。

<div @click="selectAddOn(index)" class="col-6" v-for="(addOn, index) in categories[categoryId].addOns">
    <label class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input">
        <span class="custom-control-indicator"></span>
        <span class="custom-control-description">{{ addOn.name }} (+ ${{ addOn.price }})</span>
    </label>
</div>

关于如何解决这种情况的任何想法?

2 个答案:

答案 0 :(得分:2)

当与多个复选框上的数组一起使用时,这是v-model的内置行为。您不需要click处理程序。 (代码无可奈何地从伯特的答案中解脱出来。)

&#13;
&#13;
console.clear()

new Vue({
  el: "#app",
  data:{
    selectedAddOns:[],
    categories:[
      {
        addOns:[
          {name: "AddOn One", price: 10},
          {name: "AddOn two", price: 20},
          {name: "AddOn Three", price: 30},
        ]
      },

    ],
    categoryId: 0
  }
})
&#13;
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="app">
  Selected Addons: {{selectedAddOns}}
  <div class="col-6" v-for="addOn, index in categories[categoryId].addOns">
    <label class="custom-control custom-checkbox" >
        <input type="checkbox" class="custom-control-input" :value="index" v-model="selectedAddOns" >
        <span class="custom-control-indicator"></span>
        <span class="custom-control-description">{{ addOn.name }} (+ ${{ addOn.price }})</span>
    </label>
</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

将点击事件处理程序放在input

&#13;
&#13;
console.clear()

new Vue({
  el: "#app",
  data:{
    selectedAddOns:[],
    categories:[
      {
        addOns:[
          {name: "AddOn One", price: 10},
          {name: "AddOn two", price: 20},
          {name: "AddOn Three", price: 30},
        ]
      },

    ],
    categoryId: 0
  },
  methods:{
    selectAddOn(addOnId) {
      let index = this.selectedAddOns.findIndex(a => a === addOnId)
      if (index >= 0) 
        this.selectedAddOns.splice(index, 1)
      else 
        this.selectedAddOns.push(addOnId);
    }
  }
})
&#13;
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="app">
  Selected Addons: {{selectedAddOns}}
  <div class="col-6" v-for="(addOn, index) in categories[categoryId].addOns">
    <label class="custom-control custom-checkbox" >
        <input type="checkbox" class="custom-control-input" @click="selectAddOn(index)" >
        <span class="custom-control-indicator"></span>
        <span class="custom-control-description">{{ addOn.name }} (+ ${{ addOn.price }})</span>
    </label>
</div>
</div>
&#13;
&#13;
&#13;