Jef*_*rey 17 arrays vue.js vuejs2
我创建了一个包含三个元素的组件"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?
}
}
})
Run Code Online (Sandbox Code Playgroud)
Sau*_*abh 19
你正在做的错误很少:
你可以在这里看到工作代码.
addRow(){
this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
},
removeRow(index){
this. itemList.splice(index, 1)
}
Run Code Online (Sandbox Code Playgroud)
您可以Array.push()用于将元素附加到数组。
对于删除,最好使用this.$delete(array, index)反应式对象。
Vue.delete( target, key ):删除对象上的属性。如果对象是反应性的,请确保删除会触发视图更新。这主要用于解决 Vue 无法检测属性删除的限制,但您应该很少需要使用它。
https://vuejs.org/v2/api/#Vue-delete
| 归档时间: |
|
| 查看次数: |
69479 次 |
| 最近记录: |