In-depth analysis of Vue's responsive principle and bidirectional data

In-depth analysis of Vue's responsive principle and bidirectional data

Understanding object.defineProperty to achieve responsiveness

Know what observe/watcher/dep refers to

Understand the publish-subscribe model and the specific problems it solves

There are generally two solutions to implement data responsiveness in Javascript, corresponding to the methods used by vue2.x and vue3.x respectively. They are:

Object property interception (vue2.x) Object.defineProperty
Object Proxy (vue3.x)

Tip: The following is the main content of this article. The following cases can be used for reference

What is vue-responsive?

One of Vue's most unique features is its non-intrusive reactivity system. Data models are just plain JavaScript objects. And when you modify them, the view will update. This makes state management pretty straightforward, but it's important to understand how it works so you can avoid some common problems. In this section, we will study

The low-level details of Vue's responsiveness system.

How to implement Vue-responsiveness?

Data responsiveness: The data model is just an ordinary JavaScript object, and when we modify the data, the view will be updated, avoiding frequent DOM operations and improving development efficiency. This is different from Jquery, which frequently operates DOM.

Understanding two-way data binding

When data changes, the view changes, and when the view changes, the data changes accordingly (through this sentence, we can see that data responsiveness is included in two-way binding)

We can use v-model to create two-way data binding on form elements

Data-driven is one of the most unique features of Vue

During the development process, you only need to focus on the data itself, not how the data is rendered into the view. Mainstream MVVM frameworks have implemented data responsiveness and two-way binding, so data can be bound to the DOM.

In vue.js, the so-called data-driven means that when the data changes, the user interface changes accordingly, and developers do not need to manually modify the DOM.

Understanding of data-driven:

So how does Vuejs achieve this data-driven approach?

Vue implements two-way data binding mainly by using data hijacking combined with the publisher-subscriber model, hijacking the setter and getter of each attribute through Object.defineProperty(), publishing messages to subscribers when data changes, triggering corresponding monitoring callbacks. When passing a plain JavaScript object to a Vue instance as its data option, Vue will iterate over its properties and convert them to getters/setters using Object.defineProperty. Getters/setters are not visible to the user, but internally they allow Vue to track dependencies and notify changes when properties are accessed and modified.

Vue's two-way data binding

Use MVVM as the entry point for data binding, integrate Observer, Compile and Watcher, use Observer to monitor the data changes of your own model, use Compile to parse the compilation template instructions (used to parse {{}} in Vue), and finally use Watcher to build a communication bridge between observer and Compile, so as to achieve the two-way binding effect of data change -> view update; view interaction change (input) -> data model change.

Analysis of vue-bidirectional data? /v-model The principle of two-way data binding

The code is as follows (example):

  <script>
    // Object uppercase and lowercase value writing let data = {
      name: 'Li Bai',
      age: 18
    }

    Object.keys(data).forEach(key => {
      defineReactiveProperty(data, key, data[key])
    })

    function defineReactiveProperty(data, key, value) {
      Object.defineProperty(data, key, {
        // get() {
          return value
        },
        // set value set(newVaue) {
          if (newVaue === value) {
            return
          }
          value = newVaue
          compine()
        }
      })
    }
    compine()
  </script>
</body>

</html>
 
 function compine () {
  // Get all child elements under app through document.querySelect('#app').childNodes const nodes = document.querySelector('#app').childNodes
  // Output this value. The current value is a nested array. We use foreach 
  // console.log(nodes)

  nodes.forEach(item => {
    // Output item again html:49 <input type=​"text" v-model=​"name">​ is an input input box // console.log(item)
    // Filter out the current labels, because the output of nodes will use the space as 'text' nodeType 3, and the label nodetype is 1, if judges that it is a label if (item.nodeType === 1) {
     const attrs = item.attributes
      // console.log(attrs) {0: type, 1: v-model, type: type, v-model: v-model, length: 2} returns an array Array.from(attrs).forEach(arr => {
        // console.log(arr) // texgt= 'text' v-mode: 'name' , filter out this v-model
        if (arr.nodeName === 'v-model'){
            item.value = data[arr.nodeValue]
            item.addEventListener('input',e => {
              console.log(e.target.value)
              //  
              data[arr.nodeValue] = e.target.value
            })
        }
      })
   }
  })
}

Summarize

  • The implementation of data responsiveness is nothing more than object property interception. We use Object.defineProperty to implement it, and use the Proxy object proxy solution in vue3 for optimization.
  • Several professional terms mentioned in the interview guide
    The observe object is an object that processes data into a responsive object.
    Watcher actually refers to the update function after the data changes (there are two types of watchers in Vue, one is the watcher used to update the view, and the other is the watcher declared through the watch configuration item)
    dep refers to the objects that collect update functions and trigger update functions implemented using publish and subscribe
  • The core of the instruction implementation is nothing more than finding the identifier through template compilation and then binding the data to it, and then putting it again after the data changes.
  • The essence of the publish-subscribe model is to solve the one-to-many problem and implement accurate updates after data changes in Vue.

This is the end of this article about Vue's responsive principles and bidirectional data. For more relevant Vue's responsive principles and bidirectional data content, please search for previous articles on 123WORDPRESS.COM 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 VUE responsiveness principle
  • Vue interpretation of responsive principle source code analysis
  • Example of Vue's implementation of the underlying code for simulating responsive principles
  • A brief analysis of the responsiveness principle and differences of Vue2.0/3.0
  • Detailed explanation of the data responsiveness principle of Vue
  • Detailed analysis of the Vue responsiveness principle
  • Detailed explanation of Vue3's responsive principle

<<:  Introduction to the deletion process of B-tree

>>:  Solution to the problem that VMware workstation pro cannot be opened due to win10 update

Recommend

How to install MySQL via SSH on a CentOS VPS

Type yum install mysql-server Press Y to continue...

How to connect to MySQL database using Node-Red

To connect Node-red to the database (mysql), you ...

Detailed explanation of the specific use of the ENV instruction in Dockerfile

1. The ENV instruction in the Dockerfile is used ...

JavaScript exquisite snake implementation process

Table of contents 1. Create HTML structure 2. Cre...

Why MySQL does not recommend using null columns with default values

The answer you often hear is that using a NULL va...

Limit input type (multiple methods)

1. Only Chinese characters can be input and pasted...

Practical record of vue using echarts word cloud chart

echarts word cloud is an extension of echarts htt...

Attributes and usage of ins and del tags

ins and del were introduced in HTML 4.0 to help au...

How to create a MySQL database and support Chinese characters

Let's first look at the MySQL official docume...

How to use ssh tunnel to connect to mysql server

Preface In some cases, we only know the intranet ...

Intellij IDEA quick implementation of Docker image deployment method steps

Table of contents 1. Docker enables remote access...

DHCP Configuration Tutorial in CentOS7 Environment

Table of contents Configuration command steps in ...

A brief introduction to the simple use of CentOS7 firewall and open ports

Overview (official has more detailed description)...

Web design reference firefox default style

Although W3C has established some standards for HT...

How to add a certificate to docker

1. Upgrade process: sudo apt-get update Problems ...