文章首发于集体博客 小灰灰的空间。 新人刚开始写博客记录生存,请多指教

new Vue 过程

Vue 结构器的定义

function Vue (options) {  if (process.env.NODE_ENV !== 'production' &&    !(this instanceof Vue)  ) {    // 确保只能应用 new 关键字来创立 vue 实例,而不能通过函数的一般调用形式    warn('Vue is a constructor and should be called with the `new` keyword')  }  // 进行初始化,_init 办法是 Vue 原型上的办法  this._init(options)}

初始化办法 _init

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.      // 在初始化子组件时,合并子组件的 options      initInternalComponent(vm, options)    } else {      // 内部调用 new Vue 时合并 options      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')    // 初始化 injections    initInjections(vm) // resolve injections before data/props    // 初始化 props methods data computed watch    initState(vm)    // 初始化 provide    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)    }    // 如果存在 el 选项,则调用办法挂在元素    if (vm.$options.el) {      vm.$mount(vm.$options.el)    }  }

小结

在应用 new Vue 创立 Vue 实例是,调用了原型上的 _init 办法进行初始化。次要就做了一下几件事

  • 合并配置
  • 初始化生命周期
  • 初始化工夫核心
  • 初始化渲染
  • 初始化 data props computed 等数据
  • 最初挂载元素