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

数组 Vue.js

小胖Davaid

2020-03-14

我制作了一个组件“ my-item”,其中包含三个元素:一个下拉列表(由“ itemList”填充)和两个从下拉列表填充的输入框。该组件被认为是一行。

我试图一次添加和删除一行,但我不确定两件事。(1)向行数组添加什么?(2)为什么this.rows.splice(index,1)仅删除最后一行?

https://jsbin.com/mugunum/edit?html,输出

谢谢

<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?
    }
}
})

第1613篇《如何在Vue 2中的组件中从数组添加和删除项目》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
飞云逆天 2020.03.14

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

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

Vue.delete( target, key ): Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

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

理查德Itachi 2020.03.14

您正在犯一些错误:

  1. 您需要在addRow方法中的数组中添加适当的对象
  2. 您可以使用splice方法特定索引的数组删除元素
  3. 您需要将当前行作为prop传递给my-itemcomponent,在此可以对其进行修改。

您可以在此处查看工作代码

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android