0
点赞
收藏
分享

微信扫一扫

Vue源码解析-$mount

田妞的读书笔记 2022-02-16 阅读 46

前言

Vue实例是通过mount方法进行挂载的,上一篇说了new Vue这篇分析一下mount挂载方法。mount的定义在Vue源码中有多处,这是因为Vue需要适配不同的平台以及构建方式,本文这里主要分析一下带compiler的mount实现方式。

找入口

因为是需要适配不同平台,mount方法定义在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 */
  // 报个警告,不给挂载到html和body标签上
  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重写了一遍,在重写里面添加了一些逻辑,主要就是去拿template的操作,一开始会判断一下el,看看是不是挂载到html或者body上了,是的话会报出警告,然后去拿render方法,如果没有的话就会拿el或者是template去转换为render方法,值得注意的是只有带compiler的vue版本才会去做这个render方法的转换,在runtime-only版本里面是没有的,这就是为什么使用runtime-only版本必须写render函数的原因,之后会调用一下原本的mount方法,这个mount方法定义在src/core/instance/lifecycle.js中,其实这个mount方法还是挺难找到的,只能用vscode搜索,发现重新定义mount共有三处,除了上面这处之外还有vue/src/platforms/web/runtime.js和vue/src/platforms/weex/runtime.js,重名称看应该就是vue/src/platforms/web/runtime.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)
}

就是简单地获取一下el的dom,重要的是mountComponent,这个才是挂载的主方法,定义在src/core/instance/lifecycle.js中。

mountComponent解析

道道波折找出来的主要方法,代码如下

// 函数接受3个参数,vm,el还有最后一个是服务端渲染相关参数,这里不需要分析
export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  vm.$el = el
  // 如果来到这一步还没有render函数的话那说明用户使用的是runtime-only版本但是没有定义render函数,
  //在runtime-only版本中是没有template编译到render函数的过程的
  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
        )
      }
    }
  }
  // 调用beforeMount
  callHook(vm, 'beforeMount')

  let updateComponent
  // 性能打点相关的判断,直接看else就好
  /* 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定义为匿名函数,函数调用_update方法去挂载dom,
  	//这个_update方法也是Vue里面很重要的一个方法,涵盖了vnode对比和将vnode转换为dom元素渲染到页面上,
  	//每当数据更新变化时都会被触发用来更新视图
    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
  // 这个操作很关键,这里的这个watcher是一个渲染watcher通俗地说就是掌管视图更新的,它会在初始化的时
  //候和数据更新的时候执行回调函数(就是传入的第二个参数updateComponent)
  new Watcher(vm, updateComponent, noop, {
  	// 回调执行前执行
    before () {
    //判断是不是已经挂载过,如果挂载过的就调用beforeUpdate
      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
    // 调用mounted
    callHook(vm, 'mounted')
  }
  return vm
}
举报

相关推荐

0 条评论