How to add and remove item from array in components in Vue 2 How to add and remove item from array in components in Vue 2 vue.js vue.js

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


There are few mistakes you are doing:

  1. You need to add proper object in the array in addRow method
  2. You can use splice method to remove an element from an array at particular index.
  3. You need to pass the current row as prop to my-item component, where this can be modified.

You can see working code here.

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


You can use Array.push() for appending elements to an array.

For deleting, it is best to use this.$delete(array, index) for reactive objects.

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