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

Implementation code for using mongodb database in Docker

Get the mongo image sudo docker pull mongo Run th...

Detailed steps for using jib for docker deployment in Spring Cloud

Introduction to Jib Jib is a library developed by...

Summary of 10 must-see JavaScript interview questions (recommended)

1.This points to 1. Who calls whom? example: func...

express project file directory description and detailed function description

app.js: startup file, or entry file package.json:...

Docker installation and configuration steps for MySQL

Table of contents Preface environment Install Cre...

Centos7 installation of Nginx integrated Lua sample code

Preface The computer I use is a Mac, and the oper...

MySQL 5.7.23 installation and configuration graphic tutorial

This article records the detailed installation pr...

MySQL 8.0.20 installation and configuration tutorial under Docker

Docker installs MySQL version 8.0.20 for your ref...

Understanding MySQL precompilation in one article

1. Benefits of precompilation We have all used th...

Linux uses dual network card bond and screwdriver interface

What is bond NIC bond is a technology that is com...

Detailed explanation of docker network bidirectional connection

View Docker Network docker network ls [root@maste...

Solutions to VMware workstation virtual machine compatibility issues

How to solve VMware workstation virtual machine c...

mysql8.0.23 linux (centos7) installation complete and detailed tutorial

Table of contents What is a relational database? ...

Small paging design

Let our users choose whether to move forward or ba...

Example of how to create a local user in mysql and grant database permissions

Preface When you install MySQL, you usually creat...