CodexBloom - Programming Q&A Platform

Vue 3: How to manage multiple nested reactive properties with v-model for dynamic form rendering?

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
vue.js vue-3 reactivity javascript

I've tried everything I can think of but I'm writing unit tests and I'm working on a project and hit a roadblock... Quick question that's been bugging me - I'm working on a dynamic form in Vue 3 that requires rendering multiple input fields based on a user's selection. I have a data structure that includes nested properties for each form field, and I'm having trouble ensuring that changes in these nested properties reflect correctly in the UI. For instance, I have an array of objects, each with fields for a name and age, and I want to bind these fields to inputs using `v-model`. Here's a simplified version of my setup: ```javascript <template> <div> <select v-model="selectedOption"> <option v-for="option in options" :key="option.id" :value="option.id">{{ option.label }}</option> </select> <div v-for="(item, index) in formData" :key="index"> <input v-model="item.name" placeholder="Name"/> <input v-model="item.age" type="number" placeholder="Age"/> </div> </div> </template> <script> export default { data() { return { selectedOption: null, options: [ { id: '1', label: 'Option 1' }, { id: '2', label: 'Option 2' } ], formData: [ { name: '', age: null }, { name: '', age: null } ] }; } }; </script> ``` The problem arises when I try to dynamically update `formData` based on `selectedOption`. If I change `selectedOption`, I want the `formData` array to update accordingly, yet the inputs often display stale values. I have tried using a watcher to monitor `selectedOption` and update `formData`, but the reactivity doesn't seem to work as expected. My watcher looks something like this: ```javascript watch: { selectedOption(newVal) { if (newVal === '1') { this.formData = [{ name: '', age: null }]; } else if (newVal === '2') { this.formData = [{ name: '', age: null }, { name: '', age: null }]; } } } ``` The issue I'm encountering is that when I switch options, the previously entered values seem to persist, and I receive the warning `Avoid mutating a prop directly` when I try to manipulate `formData`. How can I properly manage these nested properties and ensure the input fields are reactive and clear when changing the selection? Any guidance on best practices or alternative approaches would be greatly appreciated! What am I doing wrong? I'm working on a API that needs to handle this. Thanks in advance! For context: I'm using Javascript on macOS. The project is a CLI tool built with Javascript. How would you solve this?