You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue.js中根据数组对象的count值渲染对应数量的组件?

Solution to Render Correct Number of Form Components

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

  • getExpandedList converts 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 people array ensures each form has its own independent name and surName values—no more shared state across fields.
  • The watcher keeps the people array in sync if your category counts change dynamically.

内容的提问来源于stack exchange,提问作者oktay tontaş

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:37:43