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>
The code is pretty close. Try this.
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 anid
property for each new row object.