CodexBloom - Programming Q&A Platform

Vue 3: Handling V-Model with Nested Components and Reactive Data Issues

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
vuejs v-model reactivity Vue

I'm optimizing some code but I've been struggling with this for a few days now and could really use some help. I've looked through the documentation and I'm still confused about I'm currently facing an issue with using v-model in Vue 3 when dealing with nested components... I have a parent component that manages a list of items, and each item has its own child component where I want to edit properties of that item. However, when I try to update the item from the child component using v-model, it doesn't seem to reflect changes in the parent component as expected. This is the code structure I'm working with: In my parent component, I have: ```vue <template> <div> <ItemComponent v-for="(item, index) in items" :key="index" v-model="items[index]" /> </div> </template> <script> import ItemComponent from './ItemComponent.vue'; export default { components: { ItemComponent }, data() { return { items: [ { name: 'Item 1', value: 10 }, { name: 'Item 2', value: 20 }, ], }; }, }; </script> ``` In the child component (ItemComponent.vue), I have: ```vue <template> <div> <input v-model="localItem.name" /> <input v-model="localItem.value" type="number" /> </div> </template> <script> export default { props: ['modelValue'], data() { return { localItem: { ...this.modelValue }, }; }, watch: { localItem: { handler(newVal) { this.$emit('update:modelValue', newVal); }, deep: true, }, }, }; </script> ``` The problem arises when I modify the inputs in the child component. I see the changes locally in `localItem`, but they do not reflect back to the parent's `items` array. I expected that emitting the update with `this.$emit('update:modelValue', newVal)` would synchronize the data, but it doesn't seem to work as intended. I'm also getting this warning in the console: ``` [Vue warn]: v-model is not defined on the component instance. ``` I've attempted to directly bind the inputs to the `modelValue` prop instead of using a local copy, but that led to further issues with reactivity. How can I properly handle this use case to ensure two-way data binding works between the parent and nested child components? Is there a better approach? Has anyone else encountered this? This is my first time working with Vue 3.11. What's the correct way to implement this?