vue2与vue3源码解析对比——vue2初始化发生了什么(3)

512 阅读1分钟

new Vue发生了什么

我们以一个简单代码为例,看看vue干了哪些事情

<div id="app">{{ message }}</div>
var app = new Vue({
    el: '#app',
    data: {
    message: 'Hello Vue!'
    }
})

首先我们知道现象是页面渲染出了一个Hello Vue!

在第一章我们知道Vue是一个构造函数,所以new Vue(options)是根据配置参数实例化Vue对象,调用了this._init方法,app指向一个实例化的Vue对象

// src/core/instance/init.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对象
  this._init(options)
}

// 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') // 调用勾子beforeCreate
    initInjections(vm) // resolve injections before data/props初始化注入
    initState(vm)  // 初始化data、props、coputed、watcher
    initProvide(vm) // resolve provide after data/props 初始化provide
    callHook(vm, 'created') // 调用勾子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、coputed、watcher等等,具体的初始化逻辑我们先不分析。

在初始化的最后,检测到如果有el属性,则调用vm.$mount方法挂载vm,挂载的目标就是把模板渲染成最终的DOM,那么接下来我们来分析Vue的挂载过程。