【发布时间】:2017-09-05 18:07:54
【问题描述】:
我问了关于在how to use "v-for" for adding or removing a row with multiple components 中添加/删除行的问题
但是,我遇到了一个错误:当我添加一行时,第一行中的项目填充到第二行,当我更改第二行时,第一行也被覆盖,与第二行相同。
我一定做错了。
在.js中
var data1={selected: null, items: ["A1","B1"]};
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
}
});
var data2={selected: null, items: ["A2","B2"]};
Vue.component('comp2',{
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 data2
}
});
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)
}
},
});
在.html中
<div id="app">
<div v-for="row in rows">
<comp1></comp1>
<comp2></comp2>
<button @click="removeRow(row)">Remove Row</button>
</div>
<button @click="addRow">Add Row</button>
</div>
【问题讨论】: