Vue Checkbox array of objects:In Vue, a checkbox array of objects refers to a way of managing a list of checkboxes, where each checkbox corresponds to an object in an array. Each object contains a value that is used to determine whether the checkbox is checked or not. This is often used when you have a list of items that can be selected, and you want to keep track of which items are selected. By binding the checkboxes to the array of objects using v-model, you can easily update the selected state of each object as the user interacts with the checkboxes. This approach provides a convenient way to manage multiple checkboxes and their associated data in Vue applications.
How can I bind an array of objects to Vue checkboxes?
This Vue code creates a checkbox group that binds an array of objects to the checkboxes. The array of objects, called “items,” contains several items with an ID and a name.
The checkboxes are generated using a v-for loop that iterates through the items array and binds each item to a checkbox input.
The v-model directive binds the checked state of the checkboxes to the “selectedItems” array. Finally, the selected items are displayed using a data-binding expression in the template.
Vue Checkbox array of objects Example
<div id="app">
<h2>Select Items</h2>
<div v-for="(item, index) in items" :key="index">
<label>
<input type="checkbox" :value="item" v-model="selectedItems">
{{ item.name }}
</label>
</div>
<h2>Selected Items</h2>
{{selectedItems}}
</div>
<script>
const app = Vue.createApp({
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
{ id: 4, name: 'Item 4' },
{ id: 5, name: 'Item 5' },
],
selectedItems: [],
};
},
});
app.mount('#app');
</script>