Vue2 源码阅读(二):`new Vue()` 做了什么

在Vue开发中,我们通常使用 new Vue() 来创建一个Vue实例,就像下面这样:

new Vue({
  el: '#app',
  data: {
    message: 'Hello, Vue!'
  }
})

那当我们写下 new Vue() 时,背后究竟发生了什么呢?深入了解这一过程,有助于我们更好地理解Vue的工作原理,本文将结合Vue2的源码来详细剖析 new Vue() 内部的执行流程。

目录#

  1. 前置知识
  2. Vue 构造函数
  3. _init 方法
  4. 初始化生命周期
  5. 初始化事件
  6. 初始化渲染
  7. 挂载实例
  8. 总结
  9. 参考资料

1. 前置知识#

在阅读源码之前,我们需要了解一些基本的JavaScript和Vue相关的知识:

  • 原型链:JavaScript通过原型链实现继承,Vue 实例继承自 Vue 构造函数的原型。
  • Vue选项对象:在创建 Vue 实例时传入的对象,包含 data、methods、computed 等选项。

2. Vue 构造函数#

Vue 本质上是一个构造函数,在 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')
  }
  this._init(options)
}

从代码可以看出,Vue 构造函数首先会检查是否使用 new 关键字调用,如果不是则会发出警告。然后调用 this._init 方法进行初始化,传入用户提供的选项对象 options。

3. _init 方法#

_init 方法是Vue实例初始化的核心方法,它在 src/core/instance/init.js 中定义:

Vue.prototype._init = function (options?: Object) {
  const vm: Component = this
  // 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
    )
  }
  // 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')
 
  if (vm.$options.el) {
    vm.$mount(vm.$options.el)
  }
}

_init 方法主要做了以下几件事:

  • 合并选项:根据是否为内部组件,采用不同的方式合并选项。内部组件使用 initInternalComponent 方法,普通组件使用 mergeOptions 方法。
  • 初始化生命周期:调用 initLifecycle 方法。
  • 初始化事件:调用 initEvents 方法。
  • 初始化渲染:调用 initRender 方法。
  • 调用 beforeCreate 钩子:通过 callHook 方法触发 beforeCreate 钩子函数。
  • 初始化注入和响应式数据:依次调用 initInjections、initState 和 initProvide 方法。
  • 调用 created 钩子:通过 callHook 方法触发 created 钩子函数。
  • 挂载实例:如果提供了 el 选项,则调用 vm.$mount 方法挂载实例。

4. 初始化生命周期#

initLifecycle 方法在 src/core/instance/lifecycle.js 中定义,主要用于初始化一些与生命周期相关的属性和状态:

export function initLifecycle (vm: Component) {
  const options = vm.$options
 
  // locate first non-abstract parent
  let parent = options.parent
  if (parent && !options.abstract) {
    while (parent.$options.abstract && parent.$parent) {
      parent = parent.$parent
    }
    parent.$children.push(vm)
  }
 
  vm.$parent = parent
  vm.$root = parent ? parent.$root : vm
 
  vm.$children = []
  vm.$refs = {}
 
  vm._watcher = null
  vm._inactive = null
  vm._directInactive = false
  vm._isMounted = false
  vm._isDestroyed = false
  vm._isBeingDestroyed = false
}

该方法主要做了以下几件事:

  • 找到第一个非抽象的父组件,并将当前组件添加到父组件的 $children 数组中。
  • 初始化一些与组件关系和生命周期状态相关的属性,如 $parent、$root、$children、$refs 等。

5. 初始化事件#

initEvents 方法在 src/core/instance/events.js 中定义,用于初始化自定义事件:

export function initEvents (vm: Component) {
  vm._events = Object.create(null)
  vm._hasHookEvent = false
  // init parent attached events
  const listeners = vm.$options._parentListeners
  if (listeners) {
    updateComponentListeners(vm, listeners)
  }
}

该方法主要做了以下几件事:

  • 初始化 _events 对象,用于存储自定义事件。
  • 初始化 _hasHookEvent 标志,用于标记是否有钩子事件。
  • 如果存在父组件传递的事件监听器,则调用 updateComponentListeners 方法进行更新。

6. 初始化渲染#

initRender 方法在 src/core/instance/render.js 中定义,用于初始化渲染相关的属性和方法:

export function initRender (vm: Component) {
  vm._vnode = null // the root of the child tree
  vm._staticTrees = null // v-once cached trees
  const options = vm.$options
  const parentVnode = vm.$vnode = options._parentVnode // the placeholder node in parent tree
  const renderContext = parentVnode && parentVnode.context
  vm.$slots = resolveSlots(options._renderChildren, renderContext)
  vm.$scopedSlots = emptyObject
  // bind the createElement fn to this instance
  // so that we get proper render context inside it.
  // args order: tag, data, children, normalizationType, alwaysNormalize
  // internal version is used by render functions compiled from templates
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
  // normalization is always applied for the public version, used in
  // user-written render functions.
  vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
 
  // $attrs & $listeners are exposed for easier HOC creation.
  // they need to be reactive so that HOCs using them are always updated
  const parentData = parentVnode && parentVnode.data
 
  /* istanbul ignore else */
  if (process.env.NODE_ENV !== 'production') {
    defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, () => {
      !isUpdatingChildComponent && warn(`$attrs is readonly.`, vm)
    }, true)
    defineReactive(vm, '$listeners', options._parentListeners || emptyObject, () => {
      !isUpdatingChildComponent && warn(`$listeners is readonly.`, vm)
    }, true)
  } else {
    defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true)
    defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true)
  }
}

该方法主要做了以下几件事:

  • 初始化 _vnode 和 _staticTrees 属性。
  • 解析插槽内容,初始化 $slots 和 $scopedSlots 属性。
  • 定义 _c 和 $createElement 方法,用于创建虚拟DOM节点。
  • 将 $attrs 和 $listeners 定义为响应式属性。

7. 挂载实例#

如果在创建 Vue 实例时提供了 el 选项,则会调用 vm.$mount 方法进行挂载。$mount 方法在不同的环境下有不同的实现,在 src/platforms/web/entry-runtime-with-compiler.js 中会对其进行编译和挂载:

const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)
 
  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }
 
  const options = this.$options
  // resolve template/el and convert to render function
  if (!options.render) {
    let template = options.template
    if (template) {
      if (typeof template === 'string') {
        if (template.charAt(0) === '#') {
          template = idToTemplate(template)
          /* istanbul ignore if */
          if (process.env.NODE_ENV !== 'production' && !template) {
            warn(
              `Template element not found or is empty: ${options.template}`,
              this
            )
          }
        }
      } else if (template.nodeType) {
        template = template.innerHTML
      } else {
        if (process.env.NODE_ENV !== 'production') {
          warn('invalid template option:' + template, this)
        }
        return this
      }
    } else if (el) {
      template = getOuterHTML(el)
    }
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }
 
      const { render, staticRenderFns } = compileToFunctions(template, {
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns
 
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile end')
        measure(`vue ${this._name} compile`, 'compile', 'compile end')
      }
    }
  }
  return mount.call(this, el, hydrating)
}

$mount 方法主要做了以下几件事:

  • 检查 el 是否为 body 或 html 元素,如果是则发出警告并返回。
  • 如果没有提供 render 函数,则尝试从 template 或 el 中获取模板内容。
  • 将模板内容编译成渲染函数和静态渲染函数,并赋值给 options.render 和 options.staticRenderFns。
  • 调用原始的 $mount 方法进行挂载。

总结#

当我们使用 new Vue() 创建一个Vue实例时,主要经历了以下步骤:

  1. 检查是否使用 new 关键字调用。
  2. 合并选项。
  3. 初始化生命周期、事件和渲染相关的属性。
  4. 触发 beforeCreate 和 created 钩子。
  5. 如果提供了 el 选项,则编译模板并挂载实例。

通过深入了解 new Vue() 的执行流程,我们对Vue的初始化过程有了更清晰的认识,这有助于我们在开发中更好地使用和调试Vue应用。

参考资料#