vue中为什么可以使用this访问data中定义的变量
vue中可以使用this 直接调用data中定义的变量,如下
data: {
message: 'Hello Vue!'
},
created() {
console.log(this.message);
}
vue 2.6.12源码如下,使用defineProperty修改get set,使this.message 可以访问 this._data.message
function initData(vm) {
let data = vm.$options.data;
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {};
proxy(vm, `_data`, key)
}
function proxy(target, sourceKey, key) {
sharedPropertyDefinition.get = function proxyGetter() {
return this[sourceKey][key]
}
sharedPropertyDefinition.set = function proxySetter(val) {
this[sourceKey][key] = val
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}