1. The rationale for Vue?

When a Vue instance is created, Vue first iterates through properties in data (detecting data), converts them to getters/setters using Object.defineProperty() and internally tracks the associated dependencies, notifying changes when properties are accessed and modified. Each component instance has a corresponding Watcher, which records properties as dependencies during component rendering and then informs Watcher to recalculate when the dependencies are called by setters to update the associated components.

// Code implementation
function observe(obj){
    if(! obj ||typeofobj ! = ='object') {return
    }
    Object.keys(obj).forEach(t= >{
        defineReactive(obj,t,obj[t])
    })
    function defineReactive(obj,key,value){
        // Recursive subattributes
        observe(value)
        Object.defineProperty(obj,key{
            / / can be enumerated
            enumerable:true.// Data is configurable
            configurable:true.get:function(){
                return value
            },
            set:function(newValue){
                // If the data is an object recursive child property
                observe(newValue)
                if(newValue ! == value){ render() value = newValue } } }) } }Copy the code

[Schematic diagram]

  1. Bidirectional binding principle?

Vue uses a combination of data hijacking and subscribeer-publisher approach, using Object.defineProperty() to hijack getters and setters for individual properties and send messages to subscribers when data changes, triggering corresponding callbacks.