Vue 2.0 , data 里声明的变量,this 为何能访问直接访问的到
Vue 2.0 new Vue() 时 发生了什么
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 方法,
再看下这个_init 方法 ,会进行一系列的 初始化包括:生命周期、事件、 props、 methods、 data、 computed 与 watch 等
主要我们再看下,initState 这个方法里:
会优先判断 传入的options 是否有 props 和 methods ,有的话就进行初始化,然后再判断 是否有data,有的话也进行initData初始化
再看下 initData这个方法,先判断 data 是否是一个函数,是函数的话就进行 getData
后赋值给 vm._data,然后接着会判断data里的 key值, 是否和 props 和 methods 定义的key 冲突 最后 执行proxy 函数:
通过 Object.defineProperty 设置 setter 与 getter 函数 ,所以实际上,访问this.message ,等于访问的this._data.message