Home  >  Article  >  Web Front-end  >  How to implement two-way data binding using vue, angular, and react

How to implement two-way data binding using vue, angular, and react

亚连
亚连Original
2018-06-23 17:09:021427browse

This article mainly introduces a brief analysis of the two-way binding principles of vue, angular, and react data. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor to take a look.

Traditional approach

Front-end maintenance status, manually operate DOM to update the view. The front-end framework renders server data through templates. When the user takes an action, we manually update the DOM through document.getElementBy...
The framework helps separate data and views. Subsequent status updates require manual manipulation of the DOM, because the framework only renders for the first time and does not track status monitoring changes.

Two-way data binding

When we adopt the MV* model in front-end development, M - model refers to the model, that is, data, V - View refers to the view, which is the part of the page that is displayed. Usually, we need to write code to "render" the data obtained from the server and display it on the view. Whenever the data changes, we render again to update the view so that the view is consistent with the data.

The page will also produce changes in status and data through user interaction. At this time, we write code to synchronize the view's update of the data to the data, so that Synchronize to the backend server. That is to say,

#Different front-end MV* frameworks have different processing methods for data synchronization between Model and View. In Backbone, when transferring data from Model to View, you can listen to the change event of the Model in the View. Whenever the Model is updated, render is re-executed in the View. The data transfer from View to Model can monitor various events of the DOM elements corresponding to the View. After detecting changes in the View state, the changed data is sent to the Model (through listening events on both sides). Compared with Backbone, the MVVM framework represented by AngularJS goes a step further and supports this data synchronization mechanism from the framework level, and it is a two-way data binding:

In different In the MVVM framework, the techniques for implementing two-way data binding are different.

AngularJS adopts the "dirty value detection" method. After the data changes, it will detect the binding relationship between all data and views to identify whether any data has changed. Any changes will be processed and may be further processed. Causes changes to other data, so this process may cycle several times until no more data changes occur, then the changed data is sent to the view and the page is updated. If the data of ViewModel is changed manually, in order to ensure that the changes are synchronized to the view, a "dirty value detection" needs to be manually triggered.

VueJS uses the Object.defineProperty() method provided by ES5 to monitor operations on data, thus automatically triggering data synchronization. Moreover, since synchronization is triggered on different data, changes can be accurately sent to the bound view instead of performing a test on all data.

Vue two-way data binding realizes

The binding and synchronization of data and views is ultimately reflected in the process of reading and writing data, that is, Object.defineProperty () in the data set and get functions defined. The function in Vue is defineReactive. In the simplified version of the implementation, I only retained some basic features:

  function defineReactive(obj, key, value){
    var dep = new Dep();
    Object.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get: function reactGetter(){
        if(Dep.target){
          dep.depend();
        }
        return value;
      },
      set: function reactSetter(newVal){
        if (value === newVal) {
          return;
        } else {
          value = newVal;
          //如果数据发生改变,则通知所有的 watcher(借助 dep.notify())
          dep.notify();
        }
      }
    })
  }

When reading data, if there is currently a Watcher (an observer of the data, the watcher will Responsible for sending the new data obtained to the view), then binding the Watcher to the current data (dep.depend(), dep associates the dependencies of the current data and all watchers), which is a process of checking and recording dependencies. . When assigning data, if the data changes, all watchers will be notified (with dep.notify()). In this way, even if we change the data manually, the framework can automatically synchronize the data to the view.

Identification process of data binding relationship

In Vue and AngularJS, the binding relationship between view elements and data is added by adding instructions in HTML. Make a declaration

  <form id="test">
    <input type="text" v-model="name">
  </form>

The above HTML code indicates that the input element is bound to the name data. You can initialize it like this in JS code:

  var vm = new Vue({
   el: &#39;#test&#39;,
   data: {
    name: &#39;sysuzhyupeng&#39;
   }
  })

After the code is executed correctly, the position corresponding to the input element on the page will display the initial value given in the above code: sysuzhyupeng.

After executing vm.name = ‘zhyupeng’, the input on the page will also be updated to display: zhyupeng. Modify the content in the page text box to: yupeng, then the value obtained through vm.name is: 'yupeng'

React data binding

React uses this Method, consider the update of the virtual DOM tree:

  1. Attribute update, the component handles it by itself

  2. Structure update, re-render the subtree (virtual DOM), find the minimum change steps, package DOM operations, and patch the real DOM tree

Purely from the perspective of data binding, React virtual DOM has no data binding, because setState() does not maintain the previous state (state is discarded), and there is no binding.

From the perspective of data update mechanism, React Similar to the way of providing a data model (must be updated through state)

If there is no two-way data binding, how to implement the two-way scenario of input? Through the API provided by the framework, manual notification of data changes is very similar to the way of operating DOM

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement the cross coordinates following mouse effect in JS

How to use the EasyUI window window in jQuery

How to use laydate.js date plug-in in Angular4.0

The above is the detailed content of How to implement two-way data binding using vue, angular, and react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn