doubt

Have you ever wondered, while using Vue, why attributes defined in a data object can be accessed using an instance of Vue called this?

Let’s look at the implementation of the source code.

var sharedPropertyDefinition = {
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop }; // proxy(vm,'_data'// VM is an instance of Vue. Key is the name of the data object propertyfunction 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);
}
Copy the code

Let’s say I have a demo like this

const vm = new Vue({
    el: '#app',
    data: { message: 'Hello Vue! ' },
    created() {console.log(this.message) // Output Hello Vue! Console. log(this._data.message) // Also output Hello Vue! }})Copy the code

That is, when we write this.message like this, Vue sets a layer of proxy to this.message via Object.defineProperty and actually accesses the message property in this._data. The object this._data points to is the data object we wrote.

To the end.