首页 > 其他分享 >Vue组件是怎样挂载的

Vue组件是怎样挂载的

时间:2022-11-10 10:11:54浏览次数:73  
标签:el Vue render vm template ._ 组件 挂载 options

我们先来关注一下$mount是实现什么功能的吧:
在这里插入图片描述

我们打开源码路径core/instance/init.js:

export function initMixin (Vue: Class<Component>) {

    ......

    initLifecycle(vm)
    // 事件监听初始化
    initEvents(vm)
    initRender(vm)
    callHook(vm, 'beforeCreate')
    initInjections(vm) // resolve injections before data/props
    //初始化vm状态 prop/data/computed/watch完成初始化
    initState(vm)
    initProvide(vm) // resolve provide after data/props
    callHook(vm, 'created')

    ......

    // 配置项里有el属性, 则会挂载到真实DOM上, 完成视图的渲染
    // 这里的$mount方法,本质上调用了core/instance/liftcycle.js中的mountComponent方法
    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }
}

在这里我们怎么理解这个挂载状态呢?先来看Vue官方给的一段描述

  • 如果 Vue 实例在实例化时没有收到 el 选项,则它处于“未挂载”状态,没有关联的 DOM 元素。
  • 可以使用 vm.$mount() 手动地挂载一个未挂载的实例。
  • 如果没有提供 elementOrSelector 参数,模板将被渲染为文档之外的的元素。
  • 并且你必须使用原生DOM API 把它插入文档中。
    那我们来看一下$mount内部机制吧:
 * 缓存之前的$mount的方法以便后面返回实例,
 */
const mount = Vue.prototype.$mount
/** * 手动地挂载一个未挂载的根元素,并返回实例自身(Vue实例) */
Vue.prototype.$mount = function (
  el?: string | Element,  hydrating?: boolean
): Component {
  el = el && query(el)

  /* istanbul ignore if */
  /**   * 挂载对象不能为body和html标签   */
  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
  /**   * 判断$options是否有render方法    * 有:判断是String还是Element,获取他们的innerHTMl   * 无:在实例Vue时候在vnode里创建一个创建一个空的注释节点 见方法createEmptyVNode   */
  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
            )
          }
        }
      /**       * 获取的Element的类型       * 详细见   https://developer.mozilla.org/zh-CN/docs/Web/API/Element/outerHTML       */
      } 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 */
      /**       * 用于监控compile 的性能        */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }
       // 如果不存在 render 函数,则会将模板转换成render函数
      const { render, staticRenderFns } = compileToFunctions(template, {
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns

      /* istanbul ignore if */
       /**       * 用于监控compile 的性能       */
      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实现的是mountComponent函数功能

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

那么我们再去找一下mountComponent函数吧:

export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  vm.$el = el
  // 如果不存在render函数,则直接创建一个空的VNode节点
  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
        )
      }
    }
  }
  // 检测完render后,开始调用beforeMount声明周期
  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 = () => {
       // 这里是上面所说的观察者,这里注意第二个expOrFn参数是一个函数
      // 会在new Watcher的时候通过get方法执行一次
      // 也就是会触发第一次Dom的更新
      vm._update(vm._render(), hydrating)
    }
  }

vm._watcher = new Watcher(vm, updateComponent, noop, null, true /* isRenderWatcher */)
  hydrating = false

  //触发$mount函数
  if (vm.$vnode == null) {
    vm._isMounted = true
    callHook(vm, 'mounted')
  }
  return vm
}

参考vue实战视频讲解:进入学习

总结来说就是:

  • 执行vm._watcher = new Watcher(vm, updateComponent, noop)
  • 触发Watcher里面的get方法,设置Dep.target = watcher
  • 执行updateComponent
    这个过程中,会去读取我们绑定的数据,由于之前我们通过Observer进行了数据劫持,这样会触发数据的get方法。此时会将watcher添加到 对应的dep中。当有数据更新时,通过dep.notify()去通知到Watcher,然后执行Watcher中的update方法。此时又会去重新执行 updateComponent,至此完成对视图的重新渲染。

我们着重关注一下vm._update(vm._render(), hydrating):

...

    let vnode
    try {
      vnode = render.call(vm._renderProxy, vm.$createElement)
    } catch (e) {
      handleError(e, vm, `render`)
      // return error render result,
      // or previous vnode to prevent render error causing blank component
      /* istanbul ignore else */
      if (process.env.NODE_ENV !== 'production') {
        if (vm.$options.renderError) {
          try {
            vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
          } catch (e) {
            handleError(e, vm, `renderError`)
            vnode = vm._vnode
          }
        } else {
          vnode = vm._vnode
        }
      } else {
        vnode = vm._vnode
      }
    }

我们看到有俩个方法vm._renderProxy代理vm,要来检测render是否用了vm上没有的属性与方法,用来报错,vm.$createElement则是创建VNode:

render: function (createElement) {
  return createElement('h1', '标题')
}

数据我们是知道怎么更新的,那么组件tamplate到真实dom是怎么更新的呢?
在这里插入图片描述

  • 解析tamplate生成字符串
  • render Function处理字符串生成VNode
  • patch diff算法处理VNode

标签:el,Vue,render,vm,template,._,组件,挂载,options
From: https://www.cnblogs.com/yyds2026/p/16876157.html

相关文章

  • Vue模板是怎样编译的
    这一章我们开始讲模板解析编译:总结来说就是通过compile函数把tamplate解析成renderFunction形式的字符串compiler/index.jsimport{parse}from'./parser/index'imp......
  • Vue解决页面刷新后,用户信息丢失的问题
    解决方法:若存储的信息量较小的情况下可以使用如下方法。在App.vue中添加如下代码://在页面加载时读取sessionStorage里的状态信息if(sessionStorage.getItem('sto......
  • vue3 递归菜单组件
    有一个需求,就是不知道菜单到底有多少级,需要按照层级一层层地遍历出来递归实现的三个流程:写函数写遍历条件设置终止条件实现逻辑父请求子组件,并且把列表值转给子组......
  • vue源码分析-动态组件
    前面花了两节的内容介绍了组件,从组件的原理讲到组件的应用,包括异步组件和函数式组件的实现和使用场景。众所周知,组件是贯穿整个Vue设计理念的东西,并且也是指导我们开发的......
  • 能不能手写Vue响应式?前端面试进阶
    Vue视图更新原理Vue的视图更新原理主要涉及的是响应式相关APIObject.defineProperty的使用,它的作用是为对象的某个属性对外提供get、set方法,从而实现外部对该属性的......
  • vue面试如何准备,这几道面试题助力你拿到理想offer
    谈谈Vue和React组件化的思想1.我们在各个页面开发的时候,会产生很多重复的功能,比如element中的xxxx。像这种纯粹非页面的UI,便成为我们常用的UI组件,最初的前端组件也就仅仅......
  • 每日一题之请描述Vue组件渲染流程
    组件化是Vue,React等这些框架的一个核心思想,通过把页面拆成一个个高内聚、低耦合的组件,可以极大程度提高我们的代码复用度,同时也使得项目更加易于维护。所以,本文就来分......
  • 第2-2-1章 常见组件与中台化-中台概述
    目录1.中台概述1.1.中台概念1.2.中台背景1.3中台分类1.3.1业务中台1.3.2技术中台1.3.3研发中台1.3.4数据中台1.中台概述1.1.中台概念随着互联网公司的崛起,“......
  • 我的Vue之旅 10 Gin重写后端、实现页面详情页 Mysql + Golang + Gin
    第三期·使用Vue3.1+Axios+Golang+Mysql+Gin实现页面详情页使用Gin框架重写后端GinWebFramework(gin-gonic.com)整体代码量相比传统http写法少了30%......
  • vue--创建日历
       css使用tailwindcss <scriptsrc="https://cdn.tailwindcss.com"></script>    全部代码<template><divclass="m-auto"><h1cl......