我有一个包含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);
}
},
});
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>
答案 0 :(得分: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>
此代码将循环外的添加行按钮移动,因为您实际上并不需要多个添加行按钮。此外,循环中每个div
it adds a key,以便Vue可以在必要时正确删除组件。为了生成密钥,代码为每个新行对象创建id
属性。