如何在Vue.js中根据数组对象的count值渲染对应数量的组件?
The issue with your current code is that you're looping over each category once instead of looping count times per category. Additionally, using single name and surName variables means all text fields are bound to the same value—changing one would update all, which isn't what you want. Here's how to fix both problems:
Step 1: Expand Your Category List to Match Required Rows
First, create a computed property that generates an array with exactly the number of entries you need (3 for elders, 1 for babies, total 4). This "expanded" list will drive your v-for loop:
computed: { getList() { const getCategory = [ { category: 'elder', count: 3 }, { category: 'babies', count: 1 }, { category: 'children', count: 0 } ]; // Keep only categories with count > 0 return getCategory.filter(item => item.count > 0); }, getExpandedList() { let expanded = []; // For each category, add 'count' number of entries to the array this.getList.forEach(category => { expanded = [...expanded, ...Array(category.count).fill({ category: category.category })]; }); return expanded; } }
Step 2: Store Data for Each Individual Form
Instead of single name and surName variables, use an array of objects to hold data for each person. This ensures each text field is bound to a unique entry:
data() { return { people: [] // Each item will be { name: '', surName: '' } }; }, created() { // Initialize the people array when the component loads this.people = this.getExpandedList.map(() => ({ name: '', surName: '' })); }, watch: { // Update the people array if category counts change later getExpandedList(newList) { this.people = newList.map(() => ({ name: '', surName: '' })); } }
Step 3: Update the Template to Loop Over the People Array
Modify your template to loop over the people array, binding each text field to the corresponding person's properties:
<v-row v-for="(person, i) in people" :key="'list-item-' + i"> <v-col cols="6"> <v-text-field v-model="person.name" label="Name" /> </v-col> <v-col cols="6"> <v-text-field v-model="person.surName" label="Surname" /> </v-col> </v-row>
Why This Works
getExpandedListconverts your category counts into a flat array of entries (4 total in your example), so the v-for loop renders exactly the number of rows you need.- The
peoplearray ensures each form has its own independentnameandsurNamevalues—no more shared state across fields. - The watcher keeps the
peoplearray in sync if your category counts change dynamically.
内容的提问来源于stack exchange,提问作者oktay tontaş

