Vue源码阅读之11挂载过程概述

       当Vue组件的$options属性中具有el属性将会在此元素上进行挂载内容。

if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }

       在挂载这里就要区分Vue的一个概念,runtime only和runtime+compile,一个最主要的特征是runtime only的Vue对象中有渲染函数而runtime+compile的版本是需要经过编译生成渲染函数。

      对于runtime only版本的Vue程序将会直接执行vue-master\src\platforms\web\runtime\index.js路径下的Vue.prototype.$mount所对应的的函数,对于runtime+compile版本的函数将会先执行vue-master\src\platforms\web\entry-runtime-with-compiler.js中的Vue.prototype.$mount函数然后再执行vue-master\src\platforms\web\runtime\index.js路径下的Vue.prototype.$mount所对应的函数

   讲了一下runtime only和runtime+compile的区别之后我们继续讲解挂载执行的内容。

Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}
export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  vm.$el = el
  if (!vm.$options.render) {
    vm.$options.render = createEmptyVNode
    if (process.env.NODE_ENV !== 'production') {
      /* istanbul ignore if */
      if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') || vm.$options.el || el) {
        warn(
          'You are using the runtime-only build of Vue where the template ' +
          'compiler is not available. Either pre-compile the templates into ' +
          'render functions, or use the compiler-included build.',
          vm
        )
      } else {
        warn(
          'Failed to mount component: template or render function not defined.',
          vm
        )
      }
    }
  }
  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 = () => {
      vm._update(vm._render(), hydrating)
    }
  }
  vm._watcher = new Watcher(vm, updateComponent, noop)
  hydrating = false
  if (vm.$vnode == null) {
    vm._isMounted = true
    callHook(vm, 'mounted')
  }
  return vm
}

从上我们可以看到,首先获取挂载的元素节点,然后进行调用mountComponent函数。处理流程如下

(1)是否具有渲染函数没有则创建一个空的虚拟节点,然后就调用beforemount函数,即完成和组件的初挂载。

(2)根据是否是发布模式设置组件更新函数。

(3)设置组件的监听器属性为新建的监听器实例。

(4)根据组件的虚拟节点是否为null如果为null设置组件的挂载状态并调用组件的mounted函数

(5)最后返回组件对象。

        从上面可以看出在完成created之后便开始着手处理将组件挂载在DOM上的过程,如果是runtime only基本上将直接完成beforemount过程这个过程基本上没有做什么操作就是获取挂载元素。然后就是设置组件的更新函数然后设置组件的_watcher属性如果组件的虚拟节点的值为null则进行调用组件的hook函数,可以看出组件的mount过程主要设设置组件的更新函数和设置组件的_watcher属性。

具体的流程图如下图所示。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章