Vue.js源码阅读、三

Vue实例的挂载

前面已经提到过,在带compiler版本的实现中,platform/web/entry-runtime-with-compiler.js中,扩展了$mount方法,在调用原型上原有的$mount之前,先将字符串形式的template模版转换成render函数。
而原型上的$mount方法是在platforms/runtime/index.js中定义的:

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

调用了core/instance/lifecycle中定义的mountComponent函数
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 */
  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) {
        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
}

这段代码去掉非生产环境下的警告信息和性能分析的分支,逻辑非常清晰。
首先调用beforeMounted钩子。
然后定义了updateComponent函数,updateComponent函数会先调用vm._render方法生成虚拟DOM,也就是VNode, 然后调用vm._update更新DOM。然后实例化了一个Watcher, 在它的回调函数中会调用 updateComponent 方法。
最后设置vm._isMounted = true,表示这个实例已经挂载了。之后调用mounted钩子

这个Watcher具体是干什么用的还不太清除,后面再看

你可能感兴趣的:(Vue.js源码阅读、三)