By default when creating a checkbox using a the input checkbox tag with a v-model attribute in vue comes with some additional features as shown here. Attempts to extract this into a separate file causes it to loose these added features that come out of the box.
Here is a simple tutorial guide you in creating a custom checkbox component without any hustle.
We first need to create a vue file which will hold our component and for this tutorial we will go with CustomCheckbox.vue . You can use any name you prefer.
//CustomCheckbox.vue Script Setup approach
<template>
<input type="checkbox" v-model="model" :value="value" />
<span>{{ label }}</span>
</template>
<script setup >
import { computed, defineEmits } from "vue";
const props = defineProps({
modelValue: { type: [Array, Boolean] },
value: { type: [Boolean, Object] },
label: { type: String },
});
const emit = defineEmits(["update:modelValue"]);
const model = computed({
get() {
return props.modelValue;
},
set(value) {
emit("update:modelValue", value);
},
});
</script>
If you prefer the options api you can go with the below
//CustomCheckbox.vue Options api approach
<template>
<input type="checkbox" v-model="model" :value="value" />
<span>{{ label }}</span>
</template>
<script >
export default {
props:{
modelValue: { type: [Array, Boolean] },
value: { type: [Boolean, Object] },
label: { type: String }
},
computed:{
model:{
get() {
return this.modelValue;
},
set(value) {
this.$emit("update:modelValue", value);
}
}
}
}
</script>
With the component in place you can can simply import it and implement it like this
//File that needs to use the component
<template>
<p>
Using the custom checkbox with an array
</p>
<p>{{ selectedPeople }}</p>
<template v-for="person in people" key="person.name" >
<CustomCheckbox :label="person.name" v-model="selectedPeople" :value="person" />
</template>
<br>
<p> Using the custom checkbox as stand alone </p>
<CustomCheckbox :label="`I am checked: ${isSelected}`" v-model="isSelected" />
</template>
<script setup>
import { ref } from 'vue'
import CustomCheckbox from "./CustomCheckbox.vue"
const people = ref([
{
name:"William",
age: 30,
sex: "Male"
},
{
name:"Thomas",
age: 24,
sex: "Male"
},
{
name:"Jennifer",
age: 20,
sex: "Female"
}
]);
const selectedPeople = ref([]);
const isSelected= ref(false);
</script>
This approach wouldn't require you to write any additional code to get your custom component working with objects and arrays.
Top comments (2)
By far the best tutorial for creating custom checkbox component in Vue.
Thanks, really helped a lot. It would be nice if they would add some examples in documentation