CodexBloom - Programming Q&A Platform

Vue 3: implementing v-model Binding on Dynamically Generated Form Fields

πŸ‘€ Views: 99 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
vue.js v-model dynamic-forms JavaScript

I'm having trouble with I'm stuck on something that should probably be simple... I'm having trouble with two-way data binding using `v-model` in Vue 3 when I dynamically generate form fields based on user input. I’m trying to create a form where users can add multiple entries, but the bindings for the input fields aren't updating the state correctly. I've set up a basic form that allows users to add names to an array. When I add a new input field, I expect it to bind to the corresponding index of the array, but I see that the state does not reflect the changes made in the input fields. Sometimes, the input fields appear to be bound to the wrong index. Here’s a simplified version of my code: ```vue <template> <div> <div v-for="(name, index) in names" :key="index"> <input v-model="names[index]" placeholder="Enter name" /> </div> <button @click="addName">Add Name</button> <p>Current Names: {{ names }}</p> </div> </template> <script> export default { data() { return { names: [] }; }, methods: { addName() { this.names.push(''); } } }; </script> ``` When I add a name and then try to modify them, I see that the values are displaying correctly in the `Current Names` paragraph, but if I change one of the input fields, the value in the `names` array does not update as expected. Instead, it sometimes updates the wrong index or doesn't update at all. I’ve tried logging the `names` array after each change to debug this, but it remains unchanged until I re-focus the input or add another entry. I'm using Vue 3.2.0 and have not implemented any additional plugins or libraries. Is there a known scenario with `v-model` in this context, or am I missing something in my implementation? Any advice on how to properly bind these dynamically generated fields would be greatly appreciated! I'm working on a web app that needs to handle this. What am I doing wrong? Could this be a known issue?