vue源码学习-1.Vue实例挂载的实现

 

 

通常我们开发都是单h文件组件, 借助webpack的vue-loader, 将.vue文件里面的template编译成render函数, 这是离线时做的, 而接下来为了着重分析带compiler版本的vue, 先来看一下src/platform/web/entry-runtime-with-compiler.js 文件中定首先el不能是body html 因为挂载会替换掉整个元素, 如果能挂载再body html上面势必会造成文档的错误, 接下来我们可以看到注释// resolve template/el and convert to render function,当不存在render函数时, 将template/el 转换成render 函数, 在这里我们可以知道当没有render函数时 vue会优先去寻找配置项上的template(编译成模板的优先级是template > el)并且template还支持多种写法

1.当template时字符串时, vue会认为用户写的是id选择器, 那么就调用idToTemplate, 将其转化成模板html字符串

2.如果template是DOM节点,那么直接读取它的innerHTML

当template没有写的时候,则会拿el的outerHTML当模板之后

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, {
        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)
}

你可能感兴趣的:(vue源码学习-1.Vue实例挂载的实现)