[Vuejs]-Adding items to end of array dynamically

2👍

If I’m understanding your question correctly, you want

this.$set(this.status_arr, 'Pending', [{
  name: 'Section 1',
  count: 0
}])
👤Phil

1👍

You can change status_array to this:

{
    "Approvals": [
        {
            "name": "Section 1",
            "count": 10692
        }
    ],
    "Declines": [
        {
            "name": "Section 1",
            "count": 1212
        },
        {
            "name": "Section 2",
            "count": 5
        }
    ],
    "Pending": []
}

And when you want to add more item to Pending, you can use:

status_array.Pending.push(newEle)

Remember, Vue wraps an observed array’s mutation methods so they will also trigger view updates. The wrapped methods are:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

0👍

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object using the Vue.set or this.$set. This is how I achieve it:
A constructor function to return desirable object

 addObj(name, count) {
     return {
         name: name,
         count: count
     }
 }

Call this function

var newObj = new this.addObj('tom', 6);
this.$set(this.status_arr, 'Pending', newObj);

And if you want to remove a key val pair:

this.$delete(this.status_arr, 'Pending');

Leave a comment