[Vuejs]-How to add an object to array immediately after set to empty "[ ]" Vue

0👍

Just do this:

if (this.slugs.length > 0) {
    this.slugs = [];
}

this.slugs.push(slug);

If you have trouble with setting array to empty with assigning [] to array and loosing reactivity, then you can try next thing.

This works for me as the last resort:

var i = slugs.length;

while(i --){
    slugs.splice(i, 1);
}

You should do splice in revers mode because of index confusion: every time will be remained array element with index 1 if you will go throw the loop via

slugs.forEach((item, index) => {
    slugs.splice(index, 1);
});

And after that you can do:

this.slugs.push(slug);

Leave a comment