I get how to bind multiple checkboxes to an array in Vue. But when I try to put the checkboxes into their own component and bind to an array using v-model it doesn't seem to work. Does anyone have any idea why?
CheckboxSelection.vue
<template>
<div v-for="(check,index) in checks" :key="index">
<input v-model="model"
:value="check.value"
:id="check.id"
type="checkbox" />
</div>
</template>
<script>
export default {
props: {
value: Array
},
data(){
return {
model: this.value,
checks: [
{
id: 1,
label: 'Check 1',
value: 'check1'
},
{
id: 2,
label: 'Check 2',
value: 'check2'
}
]
}
},
watch: {
model: function(val) {
this.$emit("input", val)
}
},
}
</script>
Usage:
<CheckboxSelection v-model="selection"></CheckboxSelection>
In vue 3 value
prop has been changed to modelValue
and the emitted event input
to update:modelValue
:
export default {
props: {
modelValue: Array
},
emits:["update:modelValue"],
data(){
....
},
watch: {
model: function(val) {
this.$emit("update:modelValue", val)
}
},
}
for the script setup syntax please check my answer here