Vue 源码分析 —— 实例挂载流程

2022/3/2 22:44:59

本文主要是介绍Vue 源码分析 —— 实例挂载流程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

实例挂载基本流程

Vue 在选项合并完成之后,进行了一系列函数调用,这些函数包括了初始化事件中心、定义渲染函数等等。在 _init 方法的最后,会对象 el
选项进行判断,如果 el 选项存在,则会调用 $mount 方法挂载实例。

/* 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')


// 如果存在 el 选项,则调用方法挂在元素
if (vm.$options.el) {
  vm.$mount(vm.$options.el)
}

我们在找 $mount 方法定义时会发现,这个方法在 Vue 源码的多个位置都有定义。这是因为 $mount 方法的实现是和平台、构建方式都有关联的。在本系列的文章中,重点分析 runtime-with-compiler 版本的 $mount 方法的实现。我们先来看看 $mount 方法的实现

// 首先缓存 Vue 构造器原型上的 $mount 方法,这是一个公用的挂载方法
const mount = Vue.prototype.$mount
// 针对 runtim-with-compiler 版本重新定义  $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
  /**
   * 如果没有定义 render 方法, 则将 el 或者 template 转换成 render 方法
   */
  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 为 dom 节点
        template = template.innerHTML
      } else {
        if (process.env.NODE_ENV !== 'production') {
          warn('invalid template option:' + template, this)
        }
        return this
      }
    } else if (el) {
      // 没有传入 template 选项是,使用 el 选项对应的元素节点作为模板
      template = getOuterHTML(el)
    }
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }

      // 将 template 转换成 render 方法
      const { render, staticRenderFns } = compileToFunctions(template, {
        outputSourceRange: process.env.NODE_ENV !== 'production',
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)

      // 将转换得到的 render 方法保存到 options 中,方便后续使用
      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)
}

在这段代码中,首先缓存了 Vue 原型上的 $mount 方法(这个方法作为多个平台和环境公用的挂载方法),然后重新定义了该方法。接下来判断是否有定义 render 方法,如果没有定义 render 方法, 则需要通过 el 或者 template 选项获取到模版,然后编译模板获取到 render 方法,最后调用缓存的方法挂载元素。

现在我们来看看缓存下来的 $mount 方法的实现

// platforms/web/runtime/index.js
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

可以看到, 缓存的 $mount 内部调用了一个 mountComponent 方法(这个方法的实现会在后面分析,这里简单介绍基本功能),这个方法核心就是实例化一个渲染 Watcher,在 Wathcer 中会调用 updateComponent 方法来渲染元素。这个渲染 Watcher 会在两个地方被执行,一个是在初始化时,也就是实例挂载时;另外一个时在 Vue 实例中的数据发生变化时,重新执行来更新页面。

export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  vm.$el = el
  if (!vm.$options.render) {
    vm.$options.render = createEmptyVNode
  }
  callHook(vm, 'beforeMount')

  let updateComponent
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
    updateComponent = () => {
      const name = vm._name
      const id = vm._uid
      const startTag = `vue-perf-start:${id}`
      const endTag = `vue-perf-end:${id}`

      mark(startTag)
      const vnode = vm._render()
      mark(endTag)
      measure(`vue ${name} render`, startTag, endTag)

      mark(startTag)
      vm._update(vnode, hydrating)
      mark(endTag)
      measure(`vue ${name} patch`, startTag, endTag)
    }
  } else {
    updateComponent = () => {
      // 调用 _update 方法,将虚拟 DOM 转换成真实 DOM
      vm._update(vm._render(), hydrating)
    }
  }

  /**
   * 创建一个渲染 watcher,当数据发生变化时,会执行 updateComponent 回调函数
   * 实例在第一挂载时,也会执行一次 updateComponent 方法
   */
  new Watcher(vm, updateComponent, noop, {
    before () {
      if (vm._isMounted && !vm._isDestroyed) {
        callHook(vm, 'beforeUpdate')
      }
    }
  }, true /* isRenderWatcher */)
  hydrating = false

  // manually mounted instance, call mounted on self
  // mounted is called for render-created child components in its inserted hook
  if (vm.$vnode == null) {
    vm._isMounted = true
    callHook(vm, 'mounted')
  }
  return vm
}

总结

我们来总结一下 Vue 实例的挂载流程

  • 确定挂载的 DOM 元素,该元素不能时 htmlbody 这些根节点
  • 确定渲染方法,如果传入的选项中有定义 render 方法,则直接使用;如果为定义 render 方法,则需要通过编译模版来生成 render 方法
  • 无论 render 方法的来源是哪一种,最后都会执行 mountComponent,这个阶段会创建渲染 watcher
  • 在渲染 watcher 中回掉函数函数 updateComponent 中,会有两个阶段,一个是调用 vm._render 方法, 一个是调用 vm._update 方法,接下来将会分析这两个方法的实现和作用


这篇关于Vue 源码分析 —— 实例挂载流程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程