将非空变量分配给v模型时,复选框会自动选中所有复选框

时间:2019-06-28 03:15:29

标签: vue.js

下面是我的表单的代码,用于更新用户之前提交的数据。

<div class="myLabel">Repeat on: </div> {{ data.repeatOn }}
<div class="myInput">
   <input type="checkbox" id="1" value="1" v-model="data.repeatOn" :checked="data.repeatOn.includes('1')"><label for="1">Monday</label>&nbsp;&nbsp;
   <input type="checkbox" id="2" value="2" v-model="data.repeatOn" :checked="data.repeatOn.includes('2')"><label for="2">Tuesday</label>&nbsp;&nbsp;
   <input type="checkbox" id="3" value="3" v-model="data.repeatOn" :checked="data.repeatOn.includes('3')"><label for="3">Wednesday</label>&nbsp;&nbsp;
   <input type="checkbox" id="4" value="4" v-model="data.repeatOn" :checked="data.repeatOn.includes('4')"><label for="4">Thursday</label><br/>
   <input type="checkbox" id="5" value="5" v-model="data.repeatOn" :checked="data.repeatOn.includes('5')"><label for="5">Friday</label>&nbsp;&nbsp;
   <input type="checkbox" id="6" value="6" v-model="data.repeatOn" :checked="data.repeatOn.includes('6')"><label for="6">Saturday</label>&nbsp;&nbsp;
   <input type="checkbox" id="7" value="7" v-model="data.repeatOn" :checked="data.repeatOn.includes('7')"><label for="7">Sunday</label>&nbsp;&nbsp;
</div>

data.repeatON包含该复选框的先前选中的值。进行{{ data.repeatOn }}会显示类似1,2

的值

问题是上面的代码将始终选中所有复选框。如何仅检查data.value中存储的复选框值?

1 个答案:

答案 0 :(得分:0)

您的data.repeatOn应该在HTML上以唯一的名称进行定义,例如

<input type="checkbox" id="1" value="1" v-model="data.repeatOn[1]" :checked="data.repeatOn.includes('1')"><label for="1">Monday</label>&nbsp;&nbsp;
<input type="checkbox" id="2" value="2" v-model="data.repeatOn[2]" :checked="data.repeatOn.includes('2')"><label for="2">Tuesday</label>&nbsp;&nbsp;
//... data.repeatOn[n]

和数据

data() {
  return {
    data : {
      repeatOn : []
   }
  }
},