vue 2.0 源码略读 - data 的读取

241 阅读1分钟

Vue 2.0 , data 里声明的变量,this 为何能访问直接访问的到

image.png

Vue 2.0 new Vue() 时 发生了什么

image.png


function Vue (options) {
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }
  this._init(options)
}

通过源码,看到new Vue这个构造函数 会执行 _init 方法,

image.png

再看下这个_init 方法 ,会进行一系列的 初始化包括:生命周期、事件、 props、 methods、 data、 computed 与 watch 等

主要我们再看下,initState 这个方法里:

image.png

会优先判断 传入的options 是否有 props 和 methods ,有的话就进行初始化,然后再判断 是否有data,有的话也进行initData初始化

image.png

再看下 initData这个方法,先判断 data 是否是一个函数,是函数的话就进行 getData

image.png

后赋值给 vm._data,然后接着会判断data里的 key值, 是否和 props 和 methods 定义的key 冲突 最后 执行proxy 函数:

image.png

通过 Object.defineProperty 设置 setter 与 getter 函数 ,所以实际上,访问this.message ,等于访问的this._data.message

image.png