【问题标题】:how to use "v-for" for adding or removing a row with multiple components如何使用“v-for”添加或删除具有多个组件的行
【发布时间】:2026-01-19 21:05:02
【问题描述】:

我有一排有 3 个组件(其中定义了组件 1、组件 2 和组件 3,如我之前的问题所示: VueJs component undefined)

如何使用 v-for 添加一行或删除一行(其中包含 3 个组件)?

var data1={selected: null, items:["A", "B"]};

Vue.component('comp1', {
template: `<select v-model="selected">
         <option disabled value="">Please select</option>
         <option v-for="item in items" :value="item">{{item}}</option>
         </select>`,
data:function(){
      return data1
}              
});
 <!---similar for component 2 and 3---> 

new Vue({
  el: '#app',
  data: {
  rows:[]
  },
  methods:{
      addRow: function(){
          this.rows.push({});
              },
      removeRow: function(row){
           //console.log(row);
          this.rows.$remove(row);
             }
             },

        });

在.html中

<script src="https://unpkg.com/vue"></script>

<div id="app">
<div v-for ="row in rows">
  <comp1></comp1>
  <comp2></comp2>
  <comp3></comp3>
  <button @click="addRow">Add Row</button>
  <button @click="removeRow(row)">Remove Row</button>
</div>
</div>

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    代码非常接近。试试这个。

    console.clear()
    
    const template = {
      template: `<select v-model="selected">
             <option disabled value="">Please select</option>
             <option v-for="item in items" :value="item">{{item}}</option>
             </select>`,
      data: function() {
        return {
          selected: null,
          items: ["A", "B"]
        }
      }
    };
    
    Vue.component("comp1", template)
    Vue.component("comp2", template)
    Vue.component("comp3", template)
    
    
    new Vue({
      el: '#app',
      data: {
        rows: []
      },
      computed:{
        newId(){
         return this.rows.length == 0 ? 1 : Math.max(...this.rows.map(r => r.id)) + 1
        }
      },
      methods: {
        addRow: function() {
          this.rows.push({id: this.newId });
        },
        removeRow: function(row) {
           this.rows.splice(this.rows.indexOf(row), 1)
        }
      },
    
    });
    <script src="https://unpkg.com/vue"></script>
    
    <div id="app">
      <div v-for="row in rows" :key="row.id">
        <comp1></comp1>
        <comp2></comp2>
        <comp3></comp3>
        <button @click="removeRow(row)">Remove Row</button>
      </div>
      <button @click="addRow">Add Row</button>
    </div>

    此代码将添加行按钮移到循环之外,因为您实际上并不需要多个添加行按钮。此外,it adds a key 用于循环中的每个 div,以便 Vue 可以在必要时正确删除组件。为了生成密钥,代码为每个新行对象创建了一个id 属性。

    【讨论】:

      最近更新 更多