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

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

最佳答案

你犯的错误很少:

  1. 您需要在addRow 方法的数组中添加适当的对象
  2. 您可以使用拼接方法来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)
}

关于arrays - 如何在 Vue 2 组件的数组中添加和删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41374363/

相关文章:

JavaScript - 将 for 循环中的多个结果推送到数组中

javascript - 无法使用 this.$refs 在 Vue.js 中访问单个元素

vue.js - 如何将数据从 vuex 状态获取到本地数据进行操作

javascript - 使用 VueJS 根据复选框值切换输入元素的禁用属性

laravel - [Vue警告]:未知的自定义元素:<post>-您是否正确注册了组件?

c - 拆分字符串并将其存储到c中的数组中

Javascript - 按对象数组中对象的一个​​属性进行分组

java - 为什么 Tomcat 的 LifyCycleSupport.java 使用数组而不是任何高级容器(ArrayList)来存储监听器?

vue.js - toast 未识别

javascript - 如何使用 Vue.js 在选择选项上使用转换