$mount过程解析

151 阅读1分钟

1、在浏览器平台上的渲染过程

为了实现挂载,我们一般需要两个条件
  1. 通过el找到dom元素
  2. 存在render函数

我们平常在vue使用的写法:带编译器的写法

  1. template写法,直接写模板
  2. template为id 通过idToTemplate(template)找到模板
  3. template直接为dom 通过innerHTML找到模板
  4. 通过el去获取模板

经过 以上四种然后通过模板生成render函数

render函数的执行结果为生成了 虚拟dom

虚拟dom 通过 patch 然后实例化


1、以下代码为浏览器平台装饰器模式的$mount

目录位置: src\platforms\web\entry-runtime-with-compiler.js

作用: options从 无render函数 到 生成render函数 的 变化

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, {
        outputSourceRange: process.env.NODE_ENV !== 'production',
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns

    }
  }
  console.log(options.render)
  // 此时就已经有render函数了
  return mount.call(this, el, hydrating)
}

2、真正的原型 $mount 在 vue\src\platforms\web\runtime\index.js

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

3、关于 mountComponent 做了什么

  1. render函数规范化
  2. 调用生命周期 beforeMount
  3. 生成 updateComponent 函数
  4. 添加 Watcher
  5. 调用 mouted
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 vnode = vm._render()
      vm._update(vnode, hydrating)
    
    }
  } else {
    updateComponent = () => {
      const renderInfo = vm._render()
      console.log(renderInfo)
      vm._update(renderInfo, 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
}

4、_update函数解析

Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
    // render执行后会得到当前新的vnode
    const vm: Component = this
    const prevEl = vm.$el // 拿到之前的dom树
    const prevVnode = vm._vnode // 旧的vnode
    const restoreActiveInstance = setActiveInstance(vm)
    vm._vnode = vnode //赋值保存新的vnode
    
    
    // Vue.prototype.__patch__ is injected in entry points
    // based on the rendering backend used.
    // patch过程
    if (!prevVnode) {
      // initial render // 初始化要有多余参数
      vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
    } else {
      // updates
      vm.$el = vm.__patch__(prevVnode, vnode)
    }
    
    // 设置当前activeInstance为空
    restoreActiveInstance()
    // update __vue__ reference
    
    
    if (prevEl) {
      prevEl.__vue__ = null
    }
    if (vm.$el) {
      vm.$el.__vue__ = vm
    }
    
    // if parent is an HOC, update its $el as well
    if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
      vm.$parent.$el = vm.$el
    }
    // updated hook is called by the scheduler to ensure that children are
    // updated in a parent's updated hook.
  }