new Vue都发生了什么

187 阅读1分钟

new Vue()

c951073aa3ec41b8d09ea3afc64af20.png 从入口文件来看,new Vue只是执行了_init方法,该方法由initMixin(Vue)内部定义

// 实现_init初始化方法
export function initMixin (Vue: Class<Component>) {
  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
    // transition  keep-alive transition-group
    //合并全局的指令,组件,过滤器
    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)   //$parent,$root,$children,$refs
    initEvents(vm)    //处理父组件传递的事件和回调
    initRender(vm)    //$slots,$scopedSlots,_c,$createElement
    callHook(vm, 'beforeCreate')
    initInjections(vm) //获取注入数据
    initState(vm)     //初始化props,methods,data,computed,watch
    initProvide(vm) // 提供数据注入
    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选项时,自动调用$mount
    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }
}

所以从上面的函数来看,new Vue所做的事情分别是

  • 合并配置。 全局的指令,组件,过滤器等
  • 初始化生命周期 。 parent,parent,root,children,children,refs
  • 初始化事件中心。 处理父组件传递的事件和回调
  • 初始化渲染。slots,slots,scopedSlots,_c,$createElement
  • 调用beforeCreate钩子函数
  • 获取注入数据
  • 初始化props,methods,data,computed,watch状态
  • 提供数据注入
  • 调用created钩子函数 最终判断是否设置了el选项,如果设置了,自动调用$mount方法,执行mountComponent方法,执行挂载获取vdom并转换为dom,new Watcher()创建组件渲染watcher,updateComponent()执行初始化或更新,update()初始化或更新,将传入vdom转换为dom,初始化时执行的是dom创建操作,render()渲染组件,获取vdom。

整体流程

new Vue() => _init() => $mount() => mountComponent() =>

new Watcher() => updateComponent() => render() => _update()