I have a Vue 3 application. Within this app, I am aiming to showcase a list of items and provide users with the ability to choose items within the array. The current structure of my component is outlined below:
MyComponent.vue
<template>
<div>
<div v-for="(item, index) in getItems()" :key="`item-${itemIndex}`">
<div class="form-check">
<input class="form-check-input" :id="`checkbox-${itemIndex}`" v-model="item.selected" />
<label class="form-check-label" :for="`checkbox-${itemIndex}`">{{ item.name }} (selected: {{ item.selected }})</label>
</div>
</div>
<button class="btn" @click="generateItems">Generate Items</button>
</div>
</template>
<script>
import { reactive } from 'vue';
export default {
data() {
return itemCount: 0
},
methods: {
generateItems() {
this.itemCount = Math.floor(Math.random() * 25) + 1;
},
getItems() {
let items = reactive([]);
for (let i=0; i<this.itemCount; i++) {
items.push({
id: (i+1),
selected: false,
name: `Item #${i+1}`
});
}
return items;
}
}
}
</script>
When trying to select/deselect the checkbox, the text displaying whether it is "selected" or not does not update accordingly. This indicates that there might be an issue with how I am binding the property. At this point, I could use some guidance on what might be going wrong.
Is there a specific way to bind a checkbox to an object property within an Array in Vue 3?