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

Details after setting the iframe's src to about:blank

After setting the iframe's src to 'about:b...

JavaScript array deduplication solution

Table of contents Method 1: set: It is not a data...

How to make a List in CocosCreator

CocosCreator version: 2.3.4 Cocos does not have a...

Three ways to implement animation in CSS3

This is a test of the interviewee's basic kno...

Detailed explanation of Vue mixin usage and option merging

Table of contents 1. Use in components 2. Option ...

The presentation and opening method of hyperlink a

<br />Related articles: How to prompt and op...

How to turn a jar package into a docker container

How to turn a jar package into a docker container...

Solve the problem that Docker pulls MySQL image too slowly

After half an hour of trying to pull the MySQL im...

Html tips to make your code semantic

Html semantics seems to be a commonplace issue. G...

Docker-compose quickly builds steps for Docker private warehouse

Create docker-compose.yml and fill in the followi...

Solution to uninstalling Python and yum in CentOs system

Background of the accident: A few days ago, due t...

Detailed explanation of the use of props in React's three major attributes

Table of contents Class Component Functional Comp...

Steps to run ASP.NET Core in Docker container

There are too much knowledge to learn recently, a...