我制作了一个组件“my-item”,其中包含三个元素:一个下拉列表(由“itemList”填充)和两个从下拉列表中填充的输入框。 此组件被视为一行。
我尝试一次添加和删除一行,但有两件事我不确定。 (1) 向行数组添加什么? (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?
}
}
})
最佳答案
你犯的错误很少:
- 您需要在
addRow
方法的数组中添加适当的对象 - 您可以使用
拼接
方法来remove an element from an array在特定索引处。 - 您需要将当前行作为 prop 传递给
my-item
组件,可以在其中进行修改。
你可以看到工作代码here .
addRow(){
this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
},
removeRow(index){
this. itemList.splice(index, 1)
}
关于arrays - 如何在 Vue 2 组件的数组中添加和删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41374363/