Vue2.6.x源码阅读 - 6.源码阅读-core-组件挂载

Vue组件的挂载(mount)方法

Web平台下的 mount 方法

  • 由前几节提及的相关内容可知,platform下面在Vue共存在两个$mount方法。

  • 一个为platform/web/runtime/index.js下公共(public)的方法。

    // platform/web/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)
    }
  • 另一个为根据运行模式的不同而存在的扩展的方法,即“带编译器运行时(runtime-with-compiler)”模式下的$mount方法,位于platform/web/entry-runtime-with-compiler.js。由于方法比较长,所以依旧通过拆解的方式来看该方法。

    • 整体上看方法,除去警告部分的逻辑外,主要就通过是否含有自定义render将方法分为两部分。

      // platform/web/entry-runtime-with-compiler.js
      const mount = Vue.prototype.$mount // 记录原始(public)的 $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) {
          // 警告内容: Vue不可挂载在<body>与<html>标签上
          process.env.NODE_ENV !== 'production' && warn(
            `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
          )
          return this
        }
      
        // 通过入口文件可知,$mount方法的调用放依旧是当前Vue实例(vm),所以 this === vm
        const options = this.$options // 获取实例内属性
        // resolve template/el and convert to render function
        // 若实例内无自定义render方法,则走完template的渲染逻辑后再调用原始mount方法
        // 若实例内存在自定义render方法时,则直接调用原始的mount方法
        if (!options.render) {
          // ...
        }
        return mount.call(this, el, hydrating)
      }
    • 不含有自定义render方法时,会走原有的templaterender逻辑,将template转换为抽象语法数,提供给原始的$mount方法。

      // platform/web/entry-runtime-with-compiler.js
      // TODO:上述代码块if内的部分,待补充

最后更新于