我知道回答这个线程已经太晚了,但这可能会帮助想要在数组中验证复选框的人。
怎么工作?
这个概念很简单,必须在数组中至少选择一个复选框
在这里,当索引==0时,我想在第一个元素上显示错误,所以我应用了:rules,
然后我想检查至少选择一个元素,所以我决定在给定的以下方法中编写条件,通过alllow_validate:false。然后在计算中执行验证。
<div v-for="(checkbox , index) in yourarray" :key="index">
<v-checkbox v-if="index==0" @change="Checkboxlist()" :rules="checkbox_rules" label="iam first checkbox" :value="checkbox.cv"></v-checkbox>
<v-checkbox v-else @change="Checkboxlist()" label="checkboxfinite" :value="checkbox.checkbox_value"></v-checkbox>
</div>
2.声明数据
data(){
yourarray:[{cv:'checkbox1'},{cv:'checkbox2'},{cv:'checkbox3'}],
alllow_validate:false,
}
3.method
methods: {
Checkboxlist(){
this.$nextTick(() => {
var checked=document.querySelectorAll('input[type=checkbox]:checked');
var store="";
var firstelement=false;
for(var i=0;i<checked.length;i++){
if(checked[i].checked==true)
{
this.alllow_validate=true;
if(!firstelement){
firstelement=true;
store=checked[i].value;
}else{
store+=','+checked[i].value;
this.alllow_validate=false;
}
}
}
alert(store);
})
}
},
3.computed
computed:{
checkbox_rules(){
const rules=[];
if(this.alllow_validate){
const rule=
v => (!!v) || "Field is required";
rules.push(rule)
}
return rules;
}