Using Vue's v-bind syntax, we can bind a number of checkboxes with different value attributes to the same array, which will then contain the corresponding values of all checked checkboxes. See the example: https://vuejs.org/guide/essentials/forms.html#checkbox
Is it possible to achieve the same with custom components? Let's say I define a component CheckBox.vue as follows:
<script lang="ts" setup>
import { ref } from "vue";
const modelValue = ref(false);
const emit = defineEmits<{ "update:modelValue": [modelValue: boolean] }>();
function handle() {
modelValue.value = !modelValue.value;
emit("update:modelValue", modelValue.value);
}
</script>
<template>
<label>
<button type="button" @click="handle">
<span v-if="modelValue">✔️</span>
</button>
</label>
</template>
Now I can use v-model to synchronize a variable with the value of my custom checkbox. How can I make it so that I can also use a number of these checkboxes and bind them to an array?
Simply using the component as it is defined in the question in combination with v-bind and an array does the following: The first checkbox will add a single item to the array, which will change between true and false when clicking the checkbox. The other boxes have no effect on the array. Setting the value attribute on the button does not change this behavior.