Vue implements two-way data binding and vue binding
Vue implements two-way data binding. The details are as follows:
How does Vue implement bidirectional data binding? The answer is front-end data hijacking. Through the Object. defineProperty () method, this method can be used to set the getter and setter functions. In the setter function, you can listen to data changes and update the value of the bound element.
Bind object property changes to the UI
The general idea is:
1. Determine the bound data and use Object. defineProperty () to listen to its data changes (corresponding to defineGetAndSet)
2. Once the data changes, the setter function is triggered. Therefore, the setter function calls the callback function to trigger the update of the binding element.
3. The update of the binding element is to traverse all the binding elements, determine the function call by binding the attribute value, and pass in the modified value. (Corresponding scan)
Bind UI changes to Object Attributes
This is relatively simple, because changes to the UI will trigger some events, such as keyup. Monitors events to change data. As mentioned above, changes in data will lead to changes in the UI of elements bound to their values.
Implementation
Var data = {value: 'Hello world! '} Var bindValue; // determine the Bound Element var bindelems = [document. getElementById ('P'), document. getElementById ('input')]; // Method for modifying the value of the bound element var command = {text: function (str) {this. innerHTML = str ;}, value: function (str) {this. value = str ;}}; // traverse the Bound Element and modify its value var scan = function () {console. log ('in scan'); for (var I = 0; I <bindelems. length; I ++) {var elem = bindelems [I]; console. log ('elem ', elem); for (var j = 0; j <elem. attributes. length; j ++) {var attr = elem. attributes [j]; if (attr. nodeName. indexOf ('q-')> = 0) {command [attr. nodeName. slice (2)]. call (elem, data [attr. nodeValue]) ;}}}// sets var defineGetAndSet = function (obj, propname) {Object. defineProperty (obj, propname, {get: function () {return bindValue;}, set: function (value) {bindValue = value; scan () ;}, enumerable: true, retriable: true})} // initialize at the beginning to set the value of all bound elements to the initial value scan (); // set the element defineGetAndSet (data, 'value'); // listens for UI changes in bindelems [1]. addEventListener ('keyup', function (e) {data. value = e.tar get. value ;}); setTimeout (function () {data. value = 'change';}, 1000 );
Refer:
Two-way Data Binding using javascript
Analysis of Vue Principles & Implementation of two-way binding MVVM
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.