SoFunction
Updated on 2025-04-13

One article will help you understand the variation methods of Vue arrays

The Vue framework provides some convenient array mutation methods, including push, pop, shift, unshift, splice, sort and reverse. When developing web applications using Vue, it is often necessary to operate on arrays to achieve corresponding functions. However, when using native JavaScript array methods, you need to manually update the DOM, which seems more cumbersome. Vue's array mutation method can automatically trigger DOM updates, eliminating the steps of manually updating the DOM, allowing developers to operate array data more efficiently and improve development efficiency and code quality. Therefore, it is very necessary to understand Vue's array mutation method.

In Vue, we can use the v-for directive to render an array. For example:

<template>
  <ul>
    <li v-for="item in items" :key="">
      {{ item }}
    </li>
  </ul>
</template>
<script>
export default {
  data() {
    return {
      items: ['Apple', 'Banana', 'Orange']
    }
  }
}
</script>

In the example above, we use the v-for directive to render an array named items. This array contains three elements: Apple, Banana, and Orange. Vue automatically tracks the number of each element and updates the DOM every time the array changes.

However, sometimes we need to do some operations on the array, such as adding or removing elements. At this time, we need to use some methods of arrays, such as push, pop, splice, etc. However, these methods do not automatically trigger Vue's DOM update, so we must manually call Vue's set or set or set or forceUpdate method to update the DOM. The mutation method provided by Vue can automatically trigger DOM updates, omitting these tedious steps.

Vue provides mutation methods:

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

Let's explain in detail how these methods work.

Push method

Vue's push method is the same as JavaScript native push method, which can add one or more elements to the end of an array. For example:

('Pear');

The above code will add a new element 'Pear' to the array items. The return value of the push method is the length of the new array.

When using Vue's push method, it will automatically trigger DOM updates. This means we don't need to manually call the set or set or set or forceUpdate method to update the DOM. Vue's push method will call the native push method of the array before updating the DOM and pass the same parameters. When the array changes, Vue detects the change and updates the DOM.

It should be noted that if we add an element of object type to the array, then the object must be responsive. Otherwise, the DOM update will not be triggered when the property of this object changes. To avoid this, we should use or this.$set method to convert it into a responsive object before adding the object.

pop method

Vue's pop method is the same as JavaScript native pop method, which can delete an element from the end of the array and return the deleted element. For example:

let lastItem = ();

The above code will remove the last element from the array items and return that element. When using Vue's pop method, it will automatically trigger DOM updates without manually calling the set or set or set or forceUpdate methods.

Shift method

Vue's shift method is the same as JavaScript native shift method, which can delete an element from the head of the array and return the deleted element. For example:

The above code will remove the first element from the array items and return that element. When using Vue's shift method, it will automatically trigger DOM updates without manually calling the set or set or set or forceUpdate methods.

unshift method

Vue's unshift method is the same as JavaScript native unshift method, which can add one or more elements to the head of the array. For example:

('Grape');

The above code adds a new element 'Grape' to the head of the array items. When using Vue's unshift method, it will automatically trigger DOM updates without manually calling the set or set or set or forceUpdate methods.

splice method

Vue's splice method is the same as JavaScript native splice method, which can add or delete one or more elements anywhere. For example:

(1, 0, 'Kiwi', 'Mango');

The above code starts at index 1 in the array items, deletes 0 elements, and adds two new elements Kiwi and Mango. When using Vue's splice method, it will automatically trigger DOM updates without manually calling the set or set or set or forceUpdate methods.

It should be noted that if we add an element of object type to the array, then the object must be responsive. Otherwise, the DOM update will not be triggered when the property of this object changes. To avoid this, we should use or this.$set method to convert it into a responsive object before adding the object.

sort method

Vue's sort method is the same as JavaScript native sort method, which can sort arrays according to certain rules. For example:

();

The above code will sort the array items in alphabetical order. When using Vue's sort method, it will automatically trigger DOM updates without manually calling the set or set or set or forceUpdate methods.

It should be noted that if we want to sort the array by custom rules, then we need to pass a comparison function as the parameter of the sort method. This comparison function cannot directly modify the array, otherwise Vue will not be able to monitor changes. If we need to modify the array, we should use the mutation method.

reverse method

Vue's reverse method is the same as JavaScript native reverse method, which can arrange elements in an array in reverse order. For example

();

The above code will arrange the elements in the array items in reverse order. When using Vue's reverse method, it will automatically trigger DOM updates without manually calling the set or set or set or forceUpdate methods.

Source code analysis

Vue's array mutation method is implemented in a responsive system:

  • Dependency Tracking: When we access a property of a responsive object, Vue will automatically track the dependency to listen for changes to the property.

  • Data hijacking: Vue uses methods to convert properties of responsive objects into getters and setters, thereby realizing data hijacking, that is, automatically notify dependency updates when properties change.

  • Observer mode: Based on dependency tracking and data hijacking, Vue implements the update mechanism of a responsive system through Observer mode. When the properties of the responsive object change, the observer will receive an update notification and then perform corresponding operations, including updating the view, etc.

  • Array mutation method: Based on the responsive system, Vue implements some special array mutation methods, such as push, pop, shift, unshift, splice, sort and reverse. These methods can automatically trigger DOM updates, thereby achieving the effect of real-time updates to the view.

Vue provides some convenient array mutation methods, making it easier for us to manipulate array data. These methods automatically trigger DOM updates without manually calling the set or set or set or forceUpdate methods. But it should be noted that if we add an element of object type to the array, then the object must be responsive. Otherwise, the DOM update will not be triggered when the property of this object changes. To avoid this, we should use or this.$set method to convert it into a responsive object before adding the object.

In Vue, a global function is defineddef, used to define the attributes or methods of an object, its source code is as follows:

export function def(obj: Object, key: string, val: any, enumerable?: boolean) {
  (obj, key, {
    value: val,
    enumerable: !!enumerable,
    writable: true,
    configurable: true
  });
}

in,objRepresents the object to define a property or method,keyThe name of the attribute or method to be defined,valThe value of the attribute or method to be defined,enumerableIndicates whether the attribute or method is enumerable. This function usesMethods convert properties or methods into getters and setters.

In Vue's responsive system, array mutation methods are defined inOn, for examplepushpopshiftunshiftsplicesortandreversewait. These methods are called internallydefFunctions to define properties or methods of arrays and use()Trigger dependency update:

// Define array mutation methodconst arrayProto = ;
export const arrayMethods = (arrayProto);
['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].forEach(function (method) {
  // Cache native method  const original = arrayProto[method];
  // Dependency update will be triggered when calling array mutation methods  def(arrayMethods, method, function mutator(...args) {
    const result = (this, args);
    const ob = this.__ob__;
    let inserted;
    switch (method) {
      case 'push':
      case 'unshift':
        inserted = args;
        break;
      case 'splice':
        inserted = (2);
        break;
    }
    // Responsive processing of newly inserted elements    if (inserted) (inserted);
    ();
    return result;
  });
});

In the above source code, we first useThe method creates aNew object for prototypearrayMethods, then iterate over the array mutated methods and cache the native methods.

Subsequently, when the array mutation method is called, the dependency update is triggered and the newly inserted elements are processed responsively. Specifically, when calledpushunshiftandspliceWhen using methods such as the method, the newly inserted element will be converted into a responsive object and usedMethods observe it. Finally, use()The method triggers a dependency update, notifying the component to re-render the view.

In this way, Vue implements efficient and convenient array operation methods, and can update the DOM in real time when processing array data, improving development efficiency and code quality.

The above is a detailed article that will help you understand the variation methods of Vue arrays. For more information about Vue array mutations, please pay attention to my other related articles!