how to use “v-for” for adding or removing a row wi

2019-08-29 02:05发布

问题:

i have a row with 3 components(in which is a defined component 1, component 2 and component 3, as showed in my previous question: VueJs component undefined )

how can i add a row or remove a row (in which has 3 components) using v-for?

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);
             }
             },

        });

in .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>

回答1:

The code is pretty close. Try this.

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>

This code moves the add row button outside the loop, because you don't really need multiple add row buttons. Additionally, it adds a key for each div in the loop so that Vue can properly remove components when necessary. In order to generate the key, the code creates an id property for each new row object.