【问题标题】:How to add and remove item from array in components in Vue 2如何在 Vue 2 组件的数组中添加和删除项目
【发布时间】: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?
    }
}
})

【问题讨论】:

    标签: arrays vue.js vuejs2


    【解决方案1】:

    你犯的错误很少:

    1. 您需要在addRow方法的数组中添加适当的对象
    2. 您可以在特定索引处使用splice 方法remove an element from an array
    3. 您需要将当前行作为 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)
    }
    

    【讨论】:

    • @Pyol7 您没有在行中推送任何内容,您必须先正确修复添加行,然后您才会知道要删除的索引的区别。
    • 这就是问题所在。我不知道如何修复 addRow
    • 我是否必须将行组件推送到行数组?如果是的话怎么办?
    • @Pyol7 检查this 并编辑答案。
    • 谢谢,它的工作,但有很多重复。一定会有更好的办法。我清理了一下,但仍然不满意。
    【解决方案2】:

    您可以使用Array.push() 将元素附加到数组。

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

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

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

    【讨论】:

    猜你喜欢
    • 2014-12-23
    • 2017-01-29
    • 2021-10-03
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    相关资源
    最近更新 更多