Vue implements bidirectional data binding principle:

** Uses a combination of data hijacking and publiser-subscriber mode, using Object.defineProperty() to hijack the setter and getter of each attribute, publish messages to subscribers when data changes, and trigger corresponding listener callbacks. ** When passing a normal Javascript Object to a Vue instance as its data option, Vue iterates over its properties, turning them into getters/setters with Object.defineProperty().

Here’s a simple simulation of bidirectional binding.

The characteristics of

1. For example, input is monitored and data is pushed into the model when input is sent to change.

2. When the data in the model changes, it is mapped to the view.

Train of thought

1. Hijacking the object with defineProperty and adding getter/setter methods. Setter is executed when assigning value to the hijacked object and getter is executed when valuing the object.

2. Page monitoring is easy to think of event listeners. The input box adds an input event with an addEventListener. **

Code:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, >< title>Document</title> </head> <body> input: <input type='text' id='inputText'/><br> <span id="show"></span> </body> <script> var inputText = document.getElementById("inputText"); var show = document.getElementById("show"); / / input box to add input event inputText addEventListener (" input ", function (e) {/ / to hijack defineObj after the object is set to the input value. The value = e. arget) value; }) var defineObj = {}; DefineProperty (defineObj, 'value', {defineObj: true, Enumerable: 64x;} true, get:function() { return val; }, set: function(newVal){ val = newVal; InputText. Value = val; // Set the display value to follow the changes show.innerHTML = val; } }) </script> </html>Copy the code

The final result

Enter the value in the text input field, it will be displayed synchronously, and the memory will also change;

Change the data values in memory to map directly to the page.

Pay close attention to the public number [programming world mingshi Hidden], there are more information, example code, interview skills!