手撕Vue源码之——vue实例挂载实现方法

308 阅读2分钟

Vue实例挂载的实现

Vue中我们是通过mount实例方法去挂载vm的,mount实例方法去挂载vm的,mount方法在多个文件中都有定义,如src/platform/web/entry-runtime-with-compiler.js、src/platform/web/runtime/index.js、src/platform/weex/runtime/index.js。因为mount这个方法的实现是和平台、构建方式都有相关的。接下来我们重点分析带compiler版本的mount这个方法的实现是和平台、构建方式都有相关的。接下来我们重点分析带compiler版本的mount实现,因为抛开webpack的vue-loader,我们在出前端浏览器环境分析Vue的工作原理,有助于我们对原理理解的深入。

compiler版本的$mount实现非常有意思,先来看一下src/platform/web/entry-runtime-with-compiler.js文件中定义

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, {
        outputSourceRange: process.env.NODE_ENV !== 'production',
        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方法,在重新定义该方法,我们先来分析这段diamagnetic。首先,他对el做了限制,Vue不能挂载bodyhtml这样的根节点。接下来的是很关键的逻辑——如果没有定义render方法、则会吧el或者template字符串转换成render方法。这里我们要牢记,在Vue2.0版本中,所有Vue的组件的渲染最终都需要render方法,无论我们是用单文件.vue方法开发组件,还是写了el或者template属性,最终都会转换成render方法,那么这个过程是Vue的一个“在线编译”的过程,他是调用compileToFunctions方法实现的,编译过程我们之后会介绍。最后,调用原先原型上的mount方法,在重新定义该方法,我们先来分析这段diamagnetic。首先,他对el做了限制,Vue不能挂载body、html这样的根节点。接下来的是很关键的逻辑——如果没有定义render方法、则会吧el或者template字符串转换成render方法。这里我们要牢记,在Vue2.0版本中,所有Vue的组件的渲染最终都需要render方法,无论我们是用单文件.vue方法开发组件,还是写了el或者template属性,最终都会转换成render方法,那么这个过程是Vue的一个“在线编译”的过程,他是调用compileToFunctions方法实现的,编译过程我们之后会介绍。最后,调用原先原型上的mount方法挂载。

原先原型上的$mount方法在src/platform/web/runtime/index.js中定义,之所以这么设计完全是为了服用,因为他是可以被runtime only版本的Vue直接使用的。

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

$mount方法支持传入2个参数,第一个是el,它表示挂载的元素,可以是字符串,也可以是DOM对象,如果是字符串在浏览器环境会调用query方法转换为DOM对象的。第二个参数是和服务端渲染相关,在浏览器环境下我们不需要传第二个参数。

$mount方法实际上回去调用mountComponent方法,这个方法定义在src/core/instance/lifecycle.js文件中:

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)
    }
  }

  // we set this to vm._watcher inside the watcher's constructor
  // since the watcher's initial patch may call $forceUpdate (e.g. inside child
  // component's mounted hook), which relies on vm._watcher being already defined
  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
}

从上面的代码可以看到,mountComponent核心就是先调用vm._render方法先生成虚拟Node,在实例化一个渲染Watcher,在他的回调函数中会调用updateComponent方法,最终调用vm._update更新DOM.

Watcher在这里起到了两个作用,一个是初始化的时候会执行回调函数,另一个是当vm示例中的检测的数据发生变化的时候执行回调函数。

函数最后判断为根节点的时候设置vm._isMounted为true,表示这个实例已经挂在了,同时执行mounted钩子函数。这里注意vm.$vnode表示Vue实例的父虚拟Node,所以他为Null则表示当前是根Vue的实例。

总结

mountComponent方法的逻辑也是非常清晰的,他会完成整个渲染工作,接下来我们要重点分析其中的细节,也就是最核心的2个方法:vm._render和vm.update。