Sure! Here's an example of how you can create a nested checkbox using Vue 3 composition API and make it recursively check all its children when the parent checkbox is checked:
<template>
<div>
<ul>
<li v-for="item in data" :key="item.label">
<label>
<input type="checkbox" v-model="item.is_checked" @change="checkChildren(item)">
{{ item.label }}
</label>
<ul v-if="item.children && item.children.length">
<NestedCheckbox :data="item.children" :parentChecked="item.is_checked"></NestedCheckbox>
</ul>
</li>
</ul>
</div>
</template>
<script>
import { ref, watch } from 'vue';
export default {
name: 'NestedCheckbox',
props: {
data: {
type: Array,
required: true,
},
parentChecked: {
type: Boolean,
default: false,
},
},
setup(props) {
const checked = ref(props.parentChecked);
// Watch for changes in parentChecked prop and update checked value accordingly
watch(() => props.parentChecked, (newParentChecked) => {
checked.value = newParentChecked;
});
// Check all children recursively
const checkChildren = (item) => {
item.is_checked = checked.value;
if (item.children && item.children.length) {
item.children.forEach((child) => {
checkChildren(child);
});
}
};
return {
checked,
checkChildren,
};
},
};
</script>
In the example above, we create a component called NestedCheckbox which accepts two props: data and parentChecked. The data prop represents the nested checkbox structure and the parentChecked prop represents the checked state of the parent checkbox.
Inside the component, we create a reactive checked variable using the ref function to store the checked state of the current checkbox. We also use the watch function to watch for changes in the parentChecked prop and update the checked value accordingly.
The checkChildren function is responsible for recursively checking all children checkboxes. It updates the is_checked property of the current item and then iterates through its children (if any) to call the checkChildren function on each child.
In the template, we use v-for