vue源码中this.data,this.props的解读

vue源码src\core\instance\state.js有对状态的初始化。

即在beforeCreate钩子函数执行后会初始化$data,$props,$mounted,$watch,$computed...等方法

其中有一个功能也会在初始化中执行,那就是常用的this.data,this.props

例如图中的msg,它可以通过app.msg做更改

image.png

this.msg做出改变时,_data也会有相应的变化。

image.png

这是利用了Object.defineProperty对this.key做了拦截,当改变this.key时,也会更改this._data.key的值,代码如图:

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
    }

    // 拦截对this[key]的访问, 里面有set,get方法.
    Object.defineProperty(target, key, sharedPropertyDefinition)
}
复制代码

为了方便理解,把代码做了简化,可以复制到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('获取key', key)
            return this[sourceKey][key]
        }
        sharedPropertyDefinition.set = function proxySetter (val) {
            console.log('更新props.key', key, val)
            this[sourceKey][key] = val
        }
        Object.defineProperty(target, key, sharedPropertyDefinition)
    }

    const app = new Vue('key')
    // app.key修改后可以在app上找到props的值
    // 如 app.key = '2'; 打印app,key: '2', props: {key: '2'}
    console.log(app)
复制代码

源码中proxy的功能就是把data中的属性代理到vm实例上,通过this.key获取和修改data的值。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享