从入口代码开始剖析,咱们先来剖析 new Vue 背地产生了哪些事件。咱们都晓得,new 关键字在 Javascript 语言中代表实例化是一个对象,而 Vue 实际上是一个类,类在 Javascript 中是用 Function 来实现的,来看一下源码,在src/core/instance/index.js 中。

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')  }  // 当是实例化一个vue对象的时候  // 调用了init办法配置options  this._init(options)}

能够看到 Vue 只能通过 new 关键字初始化,而后会调用 this._init 办法, 该办法在 src/core/instance/init.js 中定义

Vue.prototype._init = function (options?: Object) {  const vm: Component = this  // a uid  vm._uid = uid++  let startTag, endTag  /* istanbul ignore if */  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {    startTag = `vue-perf-start:${vm._uid}`    endTag = `vue-perf-end:${vm._uid}`    mark(startTag)  }  // a flag to avoid this being observed  vm._isVue = true  // merge options  if (options && options._isComponent) {    // optimize internal component instantiation    // since dynamic options merging is pretty slow, and none of the    // internal component options needs special treatment.    initInternalComponent(vm, options)  } else {    vm.$options = mergeOptions(      resolveConstructorOptions(vm.constructor),      options || {},      vm    )  }  /* istanbul ignore else */  if (process.env.NODE_ENV !== 'production') {    initProxy(vm)  } else {    vm._renderProxy = vm  }  // expose real self  vm._self = vm  initLifecycle(vm)  initEvents(vm)  initRender(vm)  callHook(vm, 'beforeCreate')  initInjections(vm) // resolve injections before data/props  initState(vm)  initProvide(vm) // resolve provide after data/props  callHook(vm, 'created')  /* istanbul ignore if */  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {    vm._name = formatComponentName(vm, false)    mark(endTag)    measure(`vue ${vm._name} init`, startTag, endTag)  }  if (vm.$options.el) {    vm.$mount(vm.$options.el)  }}

Vue 初始化次要就干了几件事件,合并配置,初始化生命周期,初始化事件核心,初始化渲染,初始化 data、props、computed、watcher 等等。

Vue初始化咱们其实能够看到代码层级十分清晰。

// 对于initState()这个办法。粗疏钻研下

问题:

咱们都理解在vue中如果想要拜访Data属性的值比方
    data() {        return { b:1 }    }    // 能够间接通过this.b拜访到这个值
可是为什么会这样呢?咱们来解析下initData()这个函数
export function initState (vm: Component) {  vm._watchers = []  const opts = vm.$options  if (opts.props) initProps(vm, opts.props)  if (opts.methods) initMethods(vm, opts.methods)  if (opts.data) {  // 如果opts.data存在那么就调用initData()    initData(vm)  } else {    observe(vm._data = {}, true /* asRootData */)  }  if (opts.computed) initComputed(vm, opts.computed)  if (opts.watch && opts.watch !== nativeWatch) {    initWatch(vm, opts.watch)  }}
当初咱们来看看initData这个函数是做什么的
它接管了一个vm以后初始化的实例
function initData (vm: Component) {  let data = vm.$options.data  data = vm._data = typeof data === 'function'    ? getData(data, vm)    : data || {}  if (!isPlainObject(data)) {    data = {}    process.env.NODE_ENV !== 'production' && warn(      'data functions should return an object:\n' +      'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',      vm    )  }  // proxy data on instance  const keys = Object.keys(data)  const props = vm.$options.props  const methods = vm.$options.methods  let i = keys.length  while (i--) {    const key = keys[i]    if (process.env.NODE_ENV !== 'production') {      if (methods && hasOwn(methods, key)) {        warn(          `Method "${key}" has already been defined as a data property.`,          vm        )      }    }    if (props && hasOwn(props, key)) {      process.env.NODE_ENV !== 'production' && warn(        `The data property "${key}" is already declared as a prop. ` +        `Use prop default value instead.`,        vm      )    } else if (!isReserved(key)) {      proxy(vm, `_data`, key)    }  }  // observe data  observe(data, true /* asRootData */)}
能够看到首先对于data是否是函数和对象进行了判断,如果data是非object和function会给data赋一个空值而后warn。

之后能够看到while循环中vue对于data中的key值和props和methods做了是否反复命名的判断,如果没有反复那么就会执行

proxy(vm, `_data`, key)
proxy又是什么呢?咱们来一起看看这个函数它做了什么。
export function proxy (target: Object, sourceKey: string, key: string) {  sharedPropertyDefinition.get = function proxyGetter () {    return this[sourceKey][key]  }  sharedPropertyDefinition.set = function proxySetter (val) {    this[sourceKey][key] = val  }  Object.defineProperty(target, key, sharedPropertyDefinition)}
能够看到proxy函数接管三个参数,第一个参数是vue的实例

第二个参数是sourceKey,也就是_data

第三个参数是key值,也就是对应data的key值。

它接管这三个key值并且在以后vue实例的property上定义了一个_data的key值。value是sharedPropertyDefinition。

value是sharedPropertyDefinition上有get和set办法

所以咱们在调用this.data的时候其实就是相当于在调用this._data.data(set同理)
data() {    return {        a:'3'    }}
// 底层实现 Object.defineProperty(target, key, sharedPropertyDefinition) Object.defineProperty(vm, a, {    get(val) {        return this["_data"]["a"]    },    set(val) {    this["_data"]["a"] = val    }})