【发布时间】:2017-05-13 11:07:39
【问题描述】:
我制作了一个组件“my-item”,它包含三个元素:一个下拉列表(由“itemList”填充)和两个从下拉列表填充的输入框。 该组件被视为一行。
我正在尝试一次添加和删除一行,但有两件事我不确定。 (1) 将什么添加到 rows 数组? (2) 为什么 this.rows.splice(index,1) 只删除最后一行?
https://jsbin.com/mugunum/edit?html,output
谢谢
<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?
}
}
})
【问题讨论】: