Detailed explanation of the implementation principle of Vue2.0/3.0 two-way data binding

Detailed explanation of the implementation principle of Vue2.0/3.0 two-way data binding

The implementation principle of Vue2.0/3.0 two-way data binding

Two-way data binding simply means that changes in data can cause the page to re-render

The principle of Vue2.0 ES5:

Object.defineProperty intercepts data

Simple small case

<body>
    Name:
    <span id="name"></span>
    <br />
    <input type="text" id="inputName" />
  </body>

Changing the value of the input box changes the value in the span accordingly. The change in data can make the view

 <script>
      let obj = {
          name:''
      }
      Object.defineProperty(obj,'name',{
          get(){
                return this.name //Note that the error demonstration cannot use this to form an infinite loop and a new value must be prepared},
          set(val){

          }
      })
  </script>

Correct writing

<script>
      let obj = {
      name: ""
    };
    let newObj = JSON.parse(JSON.stringify(obj));
    Object.defineProperty(obj, "name", {
      get() {
        return newObj.name;
      },
      set(val) {
        if (val === newObj.name) return; // Increase the judgment to optimize performance. If the new value is the same as the old value, return it. If it is different, re-assign the value newObj.name = val;
        obServer();
      }
    });
    // Re-assignment method function obServer() {
      spanName.innerHTML = newObj.name; //Get the value of obj.name inputName.value = newObj.name;
    }
    obServer(); //Execute once at the beginning setTimeout(() => {
      obj.name = "大左";
    }, 1000);
  </script>

Execution Logic

1. setTimeout executes 1 second later and modifies the data to trigger obj.name's set (val)

2. Get the latest value and give it to newObj.name to execute the obServer() method

3. Get the latest value and assign spanName.innerHTML = newObj.name; inputName.value = newObj.name;

The value of the input box changes and the value of the span box changes accordingly

inputName.oninput = function() {
      obj.name = this.value;
    };

This operation is called v-model in Vue

Vue 2.0 shortcomings

1. The original data needs to be cloned, otherwise the infinite loop is mentioned above

2. If we want to intercept get and set of data in an object, we need to set the attributes in the object one by one and listen to them separately. If there are multiple attributes, we need to loop through them and listen to them separately.

Reverse look at the data in vue2.0

data(){
return {
obj:{}
}
}
this.obj.name='XXX' //This operation does not work because there is no name in obj at the beginning, so no monitoring is performed. This is caused by the second item above

OK, let's take a look at it again.

Features and benefits of 3.0

Mainly used the proxy in SE6

 <script>
    let obj = {};
    obj = new Proxy(obj, {
      get(target, prop) {
        console.log("D");
        return target[prop];
      },
      set(target, prop, value) {
        console.log("Z");
        target[prop] = value;
      }
    }); //Monitoring the entire object does not require specifying attributes, which is equivalent to monitoring all attributes in the object. So just write the overall set get
  </script>

1. Get obj.name to trigger get. There is no name here, but it can go because there is no value, so it returns undefine.

2. Set the name value to see the trigger set

3. Get obj.name again to see if there is a value

So no matter whether you have a certain attribute in the object now, because what is monitored here is the entire object, all the future ones in the object will make up for the shortcomings of 2.0

1. No need to clone

2. There is no need to set the properties of each object separately. Just set them for the entire object. It is clean and hygienic.

Implement the above 2.0 operation again

 <script>
    let obj = {};
    obj = new Proxy(obj, {
      get(target, prop) {
        console.log("D");
        return target[prop];
      },
      set(target, prop, value) {
        console.log("Z");
        target[prop] = value;
        obServer();
      }
    }); //Monitoring the entire object does not require specifying attributes, which is equivalent to monitoring all attributes in the object. So just write the overall set get
    // Re-assignment method function obServer() {
      spanName.innerHTML = obj.name; //Get the value of obj.name inputName.value = obj.name;
    }
    obServer(); //Execute once at the beginning setTimeout(() => {
      obj.name = "大左";
    }, 1000);
    inputName.oninput = function() {
      obj.name = this.value;
    };
  </script>

Summarize

This is the end of this article about the implementation principle of Vue2.0/3.0 two-way data binding. For more relevant Vue two-way data binding principle 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:
  • Detailed explanation of the two-way binding principle of Vue2.x and Vue3.x
  • Learn a little bit about Vue's data responsiveness (the difference between Vue2 and Vue3)
  • Two-way data binding method and its advantages and disadvantages in Vue3.0
  • The difference between vue2 and vue3 two-way data binding

<<:  The simplest MySQL data backup and restore tutorial in history (Part 2) (Part 36)

>>:  How to quickly deploy an Elasticsearch cluster using docker

Recommend

Solutions to MySQL OOM (memory overflow)

OOM stands for "Out Of Memory", which m...

Determine whether MySQL update will lock the table through examples

Two cases: 1. With index 2. Without index Prerequ...

Solution to Ubuntu cannot connect to the network

Effective solution for Ubuntu in virtual machine ...

React implements infinite loop scrolling information

This article shares the specific code of react to...

The marquee tag in HTML achieves seamless scrolling marquee effect

The <marquee> tag is a tag that appears in ...

In-depth explanation of iterators in ECMAScript

Table of contents Preface Earlier iterations Iter...

HTTP header information interpretation and analysis (detailed summary)

HTTP Header Explanation 1. Accept: Tells the web s...

How to reset the root password in mysql8.0.12

After installing the database, if you accidentall...

SQL Optimization Tutorial: IN and RANGE Queries

Preface "High Performance MySQL" mentio...

Installation and configuration method of Zabbix Agent on Linux platform

Here is a brief summary of the installation and c...

Sample code using vue-router in html

Introducing vue and vue-router <script src=&qu...

Implementation of navigation bar and drop-down menu in CSS

1. CSS Navigation Bar (1) Function of the navigat...