How to add and remove element from array in components in Vue 2

I created a "my-item" component that contains three items: a dropdown list (filled with "itemList") and two input fields filled in from the dropdown list. This component is considered a string.

I'm trying to add and remove one line at a time, but two things I'm not sure about. (1) what to add to the string array? (2) why does this.rows.splice (index, 1) only remove the last line?

https://jsbin.com/mugunum/edit?html,output

thank

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

      

+17


source to share


2 answers


There are several mistakes you make:

  • You need to add the correct object to the array in the method addRow

  • You can use the method splice

    to remove an element from an array at a specific index.
  • You need to pass the current string as a prop for the component my-item

    where this can be changed.


You can see the working code here .

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

      

+18


source


You can use Array.push()

to add items to an array.

Best used this.$delete(array, index)

for reactive objects for removal .



Vue.delete( target, key )

:
Delete object property. If the object is responsive, verify that the deletion triggers an update preview. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you rarely need to use it.

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

+2


source







All Articles