我制作了一个组件“ my-item”,其中包含三个元素:一个下拉列表(由“ itemList”填充)和两个从下拉列表填充的输入框。该组件被认为是一行。
我试图一次添加和删除一行,但我不确定两件事。(1)向行数组添加什么?(2)为什么this.rows.splice(index,1)仅删除最后一行?
https://jsbin.com/mugunum/edit?html,输出
谢谢
<div id="app">
<my-item v-for="(row, index) in rows"
:itemdata="itemList"
v-on:remove="removeRow(index)">
</my-item>
<div>
<button @click="addRow"> Add Row </button>
</div>
</div>
<template id="item-template">
<div>
<select v-model="selected">
<option v-for="item in itemdata" :value="item">
{{ item.code }}
</option>
</select>
<input type="text" placeholder="Text" v-model="selected.description">
<input type="text" placeholder="value" v-model="selected.unitprice">
<button v-on:click= "remove"> X </button>
</div>
</template>
Vue.component('my-item', {
props: ['itemdata'],
template: '#item-template',
data: function () {
return {
selected: this.itemdata[0]
}
},
methods: {
remove() {
this.$emit('remove');
}
}
}),
new Vue({
el: "#app",
data: {
rows: [],
itemList: [
{ code: 'Select an Item', description: '', unitprice: ''},
{ code: 'One', description: 'Item A', unitprice: '10'},
{ code: 'Two', description: 'Item B', unitprice: '22'},
{ code: 'Three', description: 'Item C', unitprice: '56'}
]
},
methods: {
addRow(){
this.rows.push(''); // what to push unto the rows array?
},
removeRow(index){
this.rows.splice(index,1); // why is this removing only the last row?
}
}
})
您可以
Array.push()
用于将元素追加到数组。对于删除,最好
this.$delete(array, index)
用于反应性对象。https://vuejs.org/v2/api/#Vue-delete