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

JavaScript imitates Taobao magnifying glass effect

This article shares the specific code for JavaScr...

Detailed explanation of how to use the vue3 Teleport instant movement function

The use of vue3 Teleport instant movement functio...

js to achieve simple drag effect

This article shares the specific code of js to ac...

Tudou.com front-end overview

1. Division of labor and process <br />At T...

SQL Server Comment Shortcut Key Operation

Batch comments in SQL Server Batch Annotation Ctr...

How to limit the number of concurrent connection requests in nginx

Introduction The module that limits the number of...

Theory: The two years of user experience

<br />It has been no more than two years sin...

Problems and solutions for MYSQL5.7.17 connection failure under MAC

The problem that MYSQL5.7.17 cannot connect under...

Python MySQL database table modification and query

Python connects to MySQL to modify and query data...

Detailed explanation of webpage screenshot function in Vue

Recently, there is a requirement for uploading pi...

How to regularly clean up docker private server images

Using CI to build docker images for release has g...

Vue shuttle box realizes up and down movement

This article example shares the specific code for...

Whitespace processing in HTML/CSS and how to preserve whitespace in the page

Whitespace rules in HTML In HTML, multiple spaces...

Graphical explanation of the underlying principle of JavaScript scope chain

Table of contents Preface Scope 1. What is scope?...