Vue.js is an MVVM framework, and the data model is just plain JavaScript objects. But as the data changes, so does the view, and he does that through a responsive system.

Object.defineproperty (reactive system via this function)

Object.defineproperty lets you make an object observable.

TestGetter () is fired when obj's key is read and testSetter () is fired when obj's key is written, which is used to update the view.Copy the code
The first parameter obj: indicates the target object. The second parameter prop: indicates the property name of the target object, such as key. The third parameter descriptor {} contains some propertiesfunction test (obj, key, val) {
        Object.defineProperty(obj, key, {
            enumerable: true, /* Optional */ signals:true, /* Attributes can be modified or deleted */ get:function testGetter () {
                returnval; Methods to get properties (depending on collection)},set: function testSetter (newVal) {
                if (newVal === val) return; Methods for setting properties // Render page methodstestRender()
            }
        });
    }
Copy the code

DefineProperty alone is not enough because we can only respond to one of the attribute values in an object. If you want to process all the properties of an object, you can use an Observer to process the object responsively by iterating through its properties.

function observer (value) {
    if(! value || (typeof value ! = ='object')) {
        return;
    }
    
    Object.keys(value).forEach((key) => {
        test(value, key, value[key]); The last reactive methodtest
    });
}
Copy the code

In the vUE source code, we can monitor the changes of the data object through the Observer so that the data changes view can be updated at any time.

Class Vue {/* Vue constructor */ constructor(options) {this._data = options.data; observer(this._data); }}Copy the code