Vue's vue.$set() method source code case detailed explanation

Vue's vue.$set() method source code case detailed explanation

In the process of using Vue to develop projects, you often encounter this problem: when an object or array (the value in the array is an object) is declared or assigned in Vue's data, adding a new attribute to the object, if the value of this attribute is updated, the view will not be updated.

This is because the newly added attributes are not responsive, so they will not trigger the view update. Usually, the static method Vue.set() or the instance method this.$set() is used to solve it. Usage:

Object: this.$set(target, key, value)

Array: this.$set(target, index, value)

But whether it is the static method Vue.set() or the instance method this.$set(), their underlying implementation logic is the same, and the implementation logic is as follows:

/**
 * Set a property on an object. Adds the new property and
 * triggers change notification if the property doesn't
 * already exists.
 */
export function set (target: Array<any> | Object, key: any, val: any): any {
  // First, determine if the target object passed in is undefined, null, primitive (original value), or throw a warning if (process.env.NODE_ENV !== 'production' &&
    (isUndef(target) || isPrimitive(target))
  ) {
    warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
  }
  // Check if the target object target is an array and key is a valid index if (Array.isArray(target) && isValidArrayIndex(key)) {
    // Take the larger value of the target array's length and key as the target's length attribute target.length = Math.max(target.length, key)
    //Replace the element at the key position through splice target.splice(key, 1, val)
    return val
  }
  // If key already exists in the target object, assign it directly if (key in target && !(key in Object.prototype)) {
    target[key] = val
    return val
  }
  // Get the observer object in target const ob = (target: any).__ob__
  // If target is a vue instance or $data returns directly if (target._isVue || (ob && ob.vmCount)) {
    process.env.NODE_ENV !== 'production' && warn(
      'Avoid adding reactive properties to a Vue instance or its root $data ' +
      'at runtime - declare it upfront in the data option.'
    )
    return val
  }
  // If ob does not exist, it means that target is not a responsive object, and the value is assigned directly without triggering a view update if (!ob) {
    target[key] = val
    return val
  }
  // If ob exists, set key as the responsive property defineReactive(ob.value, key, val)
  // Send notification to trigger view update ob.dep.notify()
  return val
}

The above is the source code of the set method in vue. It should be noted here that when processing an array, the splice method used is not the method of the array itself, but a responsive array method encapsulated in vue.

This is the end of this article about the detailed source code case of Vue's vue.$set() method. For more relevant Vue's vue.$set() method source code content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue.$set failure pitfall discovery and solution
  • Case study of dynamic data binding of this.$set in Vue
  • Vue——Solving the error Computed property "****" was assigned to but it has no setter.
  • Use of setup in vue3.0 (two ways of use)
  • A brief discussion on the precautions for using resetFields() in Vue

<<:  Detailed tutorial on how to connect to a remote server Docker to deploy a Spring Boot project in IDEA

>>:  MySQL master-slave configuration study notes

Recommend

Detailed example of using typescript to encapsulate axios in Vue3

This axios package is used in the vue3 demo. For ...

A brief discussion on the principle of React two-way data binding

Table of contents What is two-way data binding Im...

Node.js sends emails based on STMP protocol and EWS protocol

Table of contents 1 Node.js method of sending ema...

Introduction to the usage of exists and except in SQL Server

Table of contents 1. exists 1.1 Description 1.2 E...

Solution to MySQL service 1067 error: modify the mysql executable file path

Today I encountered the MySQL service 1067 error ...

How to handle spaces in CSS

1. Space rules Whitespace within HTML code is usu...

Summary of MySQL view principles and usage examples

This article summarizes the principles and usage ...

Basic installation tutorial of mysql decompression package

Since I have changed to a new computer, all the e...

Specific use of pthread_create in linux to create threads

pthread_create function Function Introduction pth...

The difference between Readonly and Disabled

To summarize: Readonly is only valid for input (te...

Why do code standards require SQL statements not to have too many joins?

Free points Interviewer : Have you ever used Linu...

Reasons and solutions for MySQL failing to create foreign keys

When associating two tables, a foreign key could ...

Solution to the problem of slow docker pull image speed

Currently, Docker has an official mirror for Chin...

Preventing SQL injection in web projects

Table of contents 1. Introduction to SQL Injectio...

Summary of commonly used CSS encapsulation methods

1. pc-reset PC style initialization /* normalize....