Deep understanding of Vue’s data responsiveness

  • 1. Getter and setter of ES syntax
  • 2. Defineproperty of ES syntax
  • 3. Vue‘s proxy and monitoring of data
  • 4. Vue’s data response

1. Getter and setter of ES syntax

Before you begin to understand Vue’s data response principle, you should first understand the specific usage of getter and setter methods in ES syntax.

Getter and setter methods are a way to add virtual properties to objects with get and set keywords. In fact, this property does not really exist, but is simulated by the value function getter and the stored value function setter. The purpose is to set the save value function and value function for an attribute to intercept the access behavior of the attribute, so as to limit the access of the attribute. As shown below (the following code comes from MDN)

Getter method

const obj = {
  log: ['a', 'b', 'c'],
  Get latest() {// add the get keyword before the normal method
    if (this.log.length == 0) {
      return undefined;
    return this.log[this.log.length - 1];

console.log(obj.latest);//  Output C and get the attribute name without parentheses

Setter method

const language = {
  set current(name) {
  log: []

language.current = 'EN';
language.current = 'FA';

console.log(language.log);// Output array ["en", "Fa"]

2. Defineproperty of ES syntax

The defineproperty method will directly define a new property on an object, or modify the existing property of an object and return the object. It can be used to modify or add properties for an object after it is defined.
The syntax is:

Object.defineProperty(obj, prop, descriptor)

Add general properties:

let data = {
  m: 0

Object.defineProperty(data, 'n', {
  Value: 1 // the value of the added attribute is its value
Console.log (` ${data. N} `) // the n value will be output as 1

It can also be used to add virtual properties of getters and setters

let data1 = {
    _n: 0

Object.defineProperty(data1, 'n', {
    return this._n
    if(value < 0) return
    this._n = value
  }//Just write get / set directly
}) // because it indicates that the virtual attribute is n, that is, get n() {}, set n (value) {}, there is no need to write n when defining the function

3. Vue’s proxy and monitoring of data

Proxy, that is, proxy. In short, I don’t handle some of my own things myself, but I hand them over to someone to help me. The person who does things is an agent. There are two key points in this logic that need to be clarified. An agent is the person who handles the operation, and the things it handles do not belong to him, but to the person who entrusts it.

Therefore, in analogy to Vue data agent, the data {} data object is the entrusted agent, and the agent found is the Vue instance VM. What the data {} data object needs to proxy VM is to manage the data operations in the data {} data object. Therefore, the data {} data object is only responsible for the production of internal data, and the management and operation of the produced data are fully entrusted to the VM.

So how does VM control and operate the data in the data {} data object? In other words, how does the VM know in time when any attribute value in the data {} data object changes?

Therefore, the getter and setter methods in ES syntax are used. Any operation of the attributes controlled by getter and setter methods will be detected by these two functions, and the attributes formed by getter and setter methods are virtual attributes, which do not really exist. Therefore, if the user wants to modify data {} directly without proxy VM The properties of the data object can not get the corresponding entity properties, and can only be modified through getter and setter methods, so its modification must be detected by the VM.

Therefore, in order to fully control the data in the data {} data object, VM must do some processing on the data {} data object when Vue instance is created. The processing is to turn the properties in the data {} data object into virtual properties controlled by getter and setter methods, save them in the proxy data object obj and return them.

However, in order to prevent the user from directly modifying the original data {} attribute, all the entity attributes of the original data {} object are changed. The added virtual attribute name is the same as the entity attribute name, and the original actual attribute will be overwritten with the virtual attribute. When the user modifies the attribute value, it is the virtual attribute modified through getter and setter methods. In this way, any change in all attributes of the data {} data object will be detected by the Vue instance VM.

let myData = {n:0}
Let data = proxy ({data: mydata}) // similar to let VM = new Vue ({data: mydata})

Function proxy ({data} / * deconstruction assignment * /){
  let _n = data.n
  Object. Defineproperty (data, 'n', {// overwrite the original data. N property
      return _n
      _n = newValue
  }) // change the attributes of the data {} data object itself. The context can be formed through closure, so that the original actual attribute value exists in the context of closure_ N medium
  const obj = {}
  Object.defineProperty(obj, 'n', {
      return data.n
      data.n = value
  }) // add a proxy for the data {} data object and operate on the data {} data object
  Return obj // obj is the proxy of data {}

4. Vue’s data response

The so-called response is that when things change, they will respond accordingly according to the change.

The data in Vue is responsive. The above Vue uses the getter and setter methods to proxy and monitor the data through the object. Defineproperty() function. Once the data changes, Vue will change the UI view corresponding to the data. This is the data response of Vue

However, if Vue uses object.defineproperty to set listening, it can only set listening for properties that already exist in the data object when Vue is instantiated, but not for properties that do not exist or are added later.

There are two ways to solve this problem:

1. Declare all attributes in advance

2. Use vue.set and this. $set to add attributes

Adding attributes using vue.set and this. $set will notify Vue to set listening operation for the added attributes.

This. $set ('This. Data ','m','10 ') // add an attribute to the VM's data object. The m value is 10

3. Array variation

For the increase of array data, the number of new data cannot be controlled, so all data values cannot be declared in advance, and set by set is too troublesome. Moreover, array is one of the commonly used object data types. Therefore, the author of Vue tampered with the addition and deletion functions of array, such as push and pop. Users still use push and pop when adding and deleting arrays in Vue, However, additional processing is carried out. These tampered APIs will add data agents to the array to listen and change the UI view according to the data response.

The above is the detailed content of in-depth understanding of Vue’s data response. For more information about Vue’s data response, please pay attention to other relevant articles of developeppaer!