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

Vue encapsulation component upload picture component

This article example shares the specific code of ...

MySQL case when usage example analysis

First we create the database table: CREATE TABLE ...

Summary of frequently used commands for Linux file operations

0. New operation: mkdir abc #Create a new folder ...

Detailed explanation of the life cycle of Angular components (Part 2)

Table of contents 1. View hook 1. Things to note ...

Should the Like function use MySQL or Redis?

Table of contents 1. Common mistakes made by begi...

js to implement verification code interference (static)

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

How to implement draggable components in Vue

This article shares with you how to implement dra...

Detailed tutorial on installing mysql 8.0.20 on CentOS7.8

1. Install MySQL software Download and install My...

Installation and deployment of MySQL Router

Table of contents 01 Introduction to MySQL Router...

Use native js to simulate the scrolling effect of live bullet screen

Table of contents 1. Basic principles 2. Specific...

Specific use of CSS content attribute

The content attribute is generally used in the ::...

TypeScript problem with iterating over object properties

Table of contents 1. Problem 2. Solution 1. Decla...

Graphic tutorial on installing Mac system in virtual machine under win10

1. Download the virtual machine version 15.5.1 I ...