如何在Vue 2中的组件中添加和删除项目中的项目

时间:2016-12-29 06:35:39

标签: 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?
    }
}
})

2 个答案:

答案 0 :(得分:15)

你犯的错误很少:

  1. 您需要在addRow方法
  2. 中的数组中添加适当的对象
  3. 您可以在特定索引处使用splice方法remove an element from an array
  4. 您需要将当前行作为prop传递给my-item组件,在此可以对其进行修改。
  5. 您可以看到工作代码here

    addRow(){
       this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
    },
    removeRow(index){
       this. itemList.splice(index, 1)
    }
    

答案 1 :(得分:1)

我认为您可以使用Array.push()将元素追加到数组。

对于删除,最好将this.$delete(array, index)用于反应对象。

  

Vue.delete( target, key ) :删除对象的属性。如果对象是反应性的,请确保删除触发视图更新。这主要是为了解决Vue无法检测到属性删除的限制,但您几乎不需要使用它。

https://vuejs.org/v2/api/#Vue-delete

相关问题