Say, I have a custom checkbox (input) component, and I plan to use it with v-model in the component that is supposed to use it.
What I'm doing is, to support multiple checkboxes, I create an array state, and upon checking/unchecking, I add/remove the checkbox's value from the array.
Is the best approach. I'm using Vue2.
// CheckBox.vue
<script>
export default {
model: { // Customising the option for model
prop: "checked", // Array of checked values
event: "check" // Firing this event with new array of checked values
},
props: ["name", "label", "value", "checked"],
emits: ["check"]
};
</script>
<template>
<label :for="`input-${name}`">
{{ label }}
<input :id="`input-${name}`" :value="value" type="checkbox" :checked="checked.includes(value)"
@change="$emit('check', $event.target.checked ? [...checked, value] : checked.filter((val) => val !== value))" /> // I'm just appending/removing value from the array state. Is this the best approach?
</label>
</template>
// SomeComponent.vue
<script>
import CheckBox from "../atoms/checkbox.vue";
export default {
data: () => ({
elements: [1, 2, 3, 4, 5, 6, 7, 8, 9],
checked: [], // Storing the checked values here
}),
watch: {
checked: function (newSelected) { console.log(newSelected); }
},
components: {
CheckBox
}
}
</script>
<template>
<ul>
<li v-for="num in elements">
<CheckBox :name="num" :label="num" :value="num" v-model="checked" />
</li>
</ul>
</template>