vue源码分析(四) 深入源码了解Vue实例的挂载

在vue源码分析(三) new Vue背后的故事 中我们了解了options选项中如果存在el属性或者直接调用$mount方法都会执行$mount方法。

一. compile中的 $mount

$mount 方法的实现与平台和构建方式有关,它是定义在Vue.prototype 上,

// src/platform/weex/runtime/index.js

Vue.prototype.$mount = function (
  el?: any,
  hydrating?: boolean
): Component {
  return mountComponent(
    this,
    el && query(el, this.$document),
    hydrating
  )
}

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


src/platform/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  or  - 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)
}
  • entry-runtime-with-compiler.js 中对src/platform/weex/runtime/index.js$mount方法作了缓存,并重新定义了自己的Vue.prototype.$mount方法
  • entry-runtime-with-compiler.js$mount方法中作了以下工作
    - 判断el是否是html 或者body 元素,命中就给出错误提示信息
    - 判断options选项是否有render方法,如果没有接着判断是否有template选项
    - 如果有template选项,会调用compileToFunctions 生成renderstaticRenderFns并添加到options选项上
    - 然后调用缓存的mount方法mount.call(this, el, hydrating)

src/platform/web/entry-runtime-with-compiler.js$mount 方法中,vue在解析生成template的过程中会对template 的类型作了猜测.如果没有render 函数有template

  • template是以#开头的id选择器会调用idToTemplate方法获取真实的html元素

    
    const idToTemplate = cached(id => {
      const el = query(id)
      return el && el.innerHTML
    })
    /**
     * Create a cached version of a pure function.
     */
    export function cached<F: Function> (fn: F): F {
      const cache = Object.create(null)  
      return (function cachedFn (str: string) {
        const hit = cache[str]
        return hit || (cache[str] = fn(str))
      }: any)
    }
    
    

    cached是一个纯函数也是一个闭包,私有变量cache缓存着通过id选择器匹配到的dom节点,结构类似于cache:{'#root':

    }
    cache是一个缓存对象,对fn(str)的结果作了缓存,再次调用cached方法时,如果str存在于cache对象中那么会直接返回结果,从而避免执行fn,这是一种使用闭包对计算结果作缓存的优化方式。

  • 如果template的结构是 会命中template.nodeType分支,这时template就是

  • 如果没有template但存在el,会调用getOuterHTML方法生成template

    
     /**
     * Get outerHTML of elements, taking care
     * of SVG elements in IE as well.
     */
    function getOuterHTML (el: Element): string {
      if (el.outerHTML) {
        return el.outerHTML
      } else {
        const container = document.createElement('div')
        container.appendChild(el.cloneNode(true))
        return container.innerHTML
      }
    }
    
    

二. runtime 中的$mount

无论时带编译功能的vue版本还是只是运行时的vue版本,最终都会执行src/platform/web/runtime/index.js中定义的$mount 方法,而$mount方法中会执行mountComponent方法。


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

三. mountComponent

src/core/instance/lifecycle.js中定义了mountComponent 方法


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 */
  // performance 与性能分析相关
  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
}

vm.$vnode == null时,认为组件挂载已经完成,调用callHook(vm, 'mounted')

该方法中主要做了以下工作

  • 定义updateComponent方法

      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)
        }
      }
    
    
  • 渲染watcher,在new watcher的过程中执行了updateComponent方法(options存在

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

四. 小结

  • 带编译功能的vue版本可以写template或者render函数,vue会调用compileToFunctions 方法将template转换成需要的render 函数
  • 如果存在templatevue会猜测template可能出现的形式,其中如果是以#开头的字符串,vuecached方法中使用闭包对计算结果作了缓存
  • vue会着重关注options对象中的render函数
  • updateComponent方法在new Watcher()中以this.get()方法执行。

你可能感兴趣的:(vue源码笔记)