What are Array Detection Mutation Methods in Vue.js

In Vue.js, array mutation methods are used to update arrays in a way that allows Vue to detect the changes and reactively update the DOM. Vue provides special methods to perform array mutations that ensure reactivity.

Array mutation methods in Vue.js

Here are the array mutation methods in Vue.js along with examples:

push() method

Adds one or more elements to the end of an array.

this.items.push(newItem);

pop() method

Removes the last element from an array.

this.items.pop();

shift() method

Removes the first element from an array.

this.items.shift();

unshift() method

Adds one or more elements to the beginning of an array.

this.items.unshift(newItem);

Splice() method

Adds or removes elements from an array at a specified index.

// Remove one element at index 1
this.items.splice(1, 1);

// Add one element at index 2
this.items.splice(2, 0, newItem);

sort() method

Sorts the elements of an array in place and updates the array.

this.items.sort();

reverse() method

Reverses the order of the elements in an array.

this.items.reverse();

filter() method

Creates a new array with elements that pass a test function.

this.items = this.items.filter(item => item !== itemToRemove);

concat() method

Concatenates two or more arrays and returns a new array.

const newArray = this.items.concat(otherArray);

slice() method

Returns a shallow copy of a portion of an array into a new array.

const newArray = this.items.slice(startIndex, endIndex);

Vue.set() method

Adds a new property to reactive data and ensures that Vue detects the change.

Vue.set(this.items, index, newValue);

Vue.delete() method

Deletes a property from reactive data and ensures that Vue detects the change.

Vue.delete(this.items, index);

These array mutation methods ensure that Vue.js can detect changes to arrays and update the DOM reactively, maintaining the reactivity of your Vue components. It's essential to use these methods when working with reactive arrays in Vue.js applications to avoid reactivity caveats.