Vue source code SRC \core\instance\state.js has initialization of state.

$data,$props,$Mounted,$watch,$computed… Methods such as

One of the functions that is also executed during initialization is the usual this.data,this.props

For example, MSG in the picture can be changed via app.msg

When this. MSG is changed, _data is also changed accordingly.

Object.defineproperty intercepts this.key. When this. Key is changed, the value of this._data.key is also changed.

function proxy (target, sourceKey, key) {
    sharedPropertyDefinition.get = function proxyGetter () {
        return this[sourceKey][key]
    }

    sharedPropertyDefinition.set = function proxySetter (val) {
        console.log(val, sourceKey, key)
        this[sourceKey][key] = val
    }

    // Block access to this[key].
    Object.defineProperty(target, key, sharedPropertyDefinition)
}
Copy the code

To make it easier to understand, the code has been simplified and can be copied to run in F12:

    function Vue (s) {
        this._init(s)
    }
    
    Vue.prototype._init = function (s) {
        const vm = this
        vm.props = {}
        proxy(vm, 'props', s)
    }

    const sharedPropertyDefinition = {
        enumerable: true.configurable: true.get: function () {},
        set: function () {}}function proxy (target, sourceKey, key) {
        sharedPropertyDefinition.get = function proxyGetter () {
            console.log('access to key', key)
            return this[sourceKey][key]
        }
        sharedPropertyDefinition.set = function proxySetter (val) {
            console.log('update props. Key', key, val)
            this[sourceKey][key] = val
        }
        Object.defineProperty(target, key, sharedPropertyDefinition)
    }

    const app = new Vue('key')
    // app.key after modification, you can find the props value on app
    // app.key = '2'; Print app, key: '2', props: {key: '2'}
    console.log(app)
Copy the code

The function of proxy in the source code is to proxy the attributes in data to the VM instance, and obtain and modify the value of data through this.key.