Vue组件是怎样挂载的

news2024/9/29 15:23:35

我们先来关注一下$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
}

总结来说就是:

  • 执行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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/375314.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

FastDDS-3. DDS层

3. DDS层 eProsima Fast DDS公开了两个不同的API&#xff0c;以在不同级别与通信服务交互。主要API是数据分发服务&#xff08;DDS&#xff09;数据中心发布订阅&#xff08;DCPS&#xff09;平台独立模型&#xff08;PIM&#xff09;API&#xff0c;简称DDS DCPS PIM&#xf…

nacos集群模式+keepalived搭建高可用服务

实际工作中如果nacos这样的核心服务停掉了或者整个服务器宕机了&#xff0c;那整个系统也就gg了&#xff0c;所以像这样的核心服务我们必须要搞个3个或者3个以上的nacos集群部署&#xff0c;实现高可用&#xff1b; 部署高可用版本之前&#xff0c;首先你要会部署单机版的naco…

[2]MyBatis+Spring+SpringMVC+SSM整合一套通关

二、Spring 1、Spring简介 1.1、Spring概述 官网地址&#xff1a;https://spring.io/ Spring 是最受欢迎的企业级 Java 应用程序开发框架&#xff0c;数以百万的来自世界各地的开发人员使用 Spring 框架来创建性能好、易于测试、可重用的代码。 Spring 框架是一个开源的 Jav…

激活函数入门学习

本篇文章从外行工科的角度尽量详细剖析激活函数&#xff0c;希望不吝指教&#xff01; 学习过程如下&#xff0c;先知道这个东西是什么&#xff0c;有什么用处&#xff0c;以及怎么使用它&#xff1a; 1. 为什么使用激活函数 2. 激活函数总类及优缺点 3. 如何选择激活函数 …

一篇了解模块打包工具之 ——webpack(1)

本篇采用问题引导的方式来学习webpack&#xff0c;借此梳理一下自己对webpack的理解&#xff0c;将所有的知识点连成一条线&#xff0c;形成对webpack的记忆导图。 最终目标&#xff0c;手动构建一个vue项目&#xff0c;目录结构参考vue-cli创建出来的项目 一、问问题 1. 第…

Echarts 仪表盘倾斜一定角度显示,非中间对称

第024个点击查看专栏目录大多数的情况下&#xff0c;制作的仪表盘都是中规中矩&#xff0c;横向中间对称&#xff0c;但是生活中的汽车&#xff0c;摩托车等仪表盘确是要倾斜一定角度的&#xff0c;Echarts中我们就模拟一个带有倾斜角度的仪表盘。核心代码见示例源代码 文章目录…

搞明白redis的这些问题,你就是redis高手

什么是redis? Redis 本质上是一个 Key-Value 类型的内存数据库&#xff0c; 整个数据库加载在内存当中进行操作&#xff0c; 定期通过异步操作把数据库数据 flush 到硬盘上进行保存。 因为是纯内存操作&#xff0c; Redis 的性能非常出色&#xff0c; 每秒可以处理超过 10 万…

JS 快速创建二维数组 fill方法的坑点

JS 快速创建二维数组 坑 在算法中&#xff0c;创建二维数组遇到的一个坑 const arr new Array(5).fill(new Array(2).fill(1))我们如果想要修改其中一个元素的值 arr[0][1] 5我们可以发现所有数组中的第二个元素都发生了改变 查看MDN&#xff0c;我们会发现&#xff0c;当…

2023前端二面经典手写面试题

实现一个call call做了什么: 将函数设为对象的属性执行&删除这个函数指定this到函数并传入给定参数执行函数如果不传入参数&#xff0c;默认指向为 window // 模拟 call bar.mycall(null); //实现一个call方法&#xff1a; Function.prototype.myCall function(context…

一篇搞懂springboot多数据源

好文推荐 https://zhuanlan.zhihu.com/p/563949762 mybatis 配置多数据源 参考文章 https://blog.csdn.net/qq_38353700/article/details/118583828 使用mybatis配置多数据源我接触过的有两种方式&#xff0c;一种是通过java config的方式手动配置两个数据源&#xff0c;…

01、SVN 概述

SVN 概述1 概述2 功能3 工作原理4 基本操作1 概述 Apache下的一个开源的项目Subversion&#xff0c;通常缩写为 SVN&#xff0c;是一个版本控制系统版本控制系统是一个软件&#xff0c;它可以伴随我们软件开发人员一起工作&#xff0c;让编写代码的完整的历史保存下来目前它的…

数仓基础与hive入门

目录1、数仓数据仓库主流开发语言--SQL2、Apache Hive入门2.1 hive定义2.2 为什么使用Hive2.3 Hive和Hadoop关系2.4 场景设计&#xff1a;如何模拟实现Hive功能2.5 Apache Hive架构、组件3、Apache Hive安装部署3.1 metastore配置方式4、Hive SQL语言&#xff1a;DDL建库、建表…

内存保护_2:RTA-OS内存保护逻辑及配置说明

上一篇 | 返回主目录 | 下一篇 内存保护_2&#xff1a;RTA-OS内存保护逻辑及配置说明3 OS配置说明3.1 OS一些基本概念及相互关系3.1.1 基本概念3.1.2 相互关系3.2 内存保护基本逻辑&#xff08;RTA-OS&#xff09;3.2.1 应用集的基本分类3.2.2 内存保护与应用集的关系3.3 OS等级…

七大排序(Java)

目录 一、插入排序 1. 直接插入排序 2. 希尔排序 二、选择排序 1. 直接选择排序 2. 堆排序 三、交换排序 1. 冒泡排序 2. 快速排序 四、归并排序 五、总结 一、插入排序 1. 直接插入排序 抓一张牌&#xff0c;在有序的牌中&#xff0c;找到合适的位置并且插入。 时间…

三战阿里测试岗,成功上岸,面试才是测试员涨薪真正的拦路虎...

第一次面试阿里记得是挂在技术面上&#xff0c;当时也是技术不扎实&#xff0c;准备的不充分&#xff0c;面试官出的面试题确实把我问的一头雾水&#xff0c;还没结束我就已经知道我挂了这次面试。 第二次面试&#xff0c;我准备的特别充分&#xff0c;提前刷了半个月的面试题…

防止jar被反编译 不安装jdk运行jar

防止jar被反编译1.pom.xml<repositories><repository><id>jitpack</id><url>https://jitpack.io</url></repository> </repositories><dependencies><dependency><groupId>org.openjfx</groupId><…

RabbitMQ死信队列

目录 一、概念 二、出现死信的原因 三、实战 &#xff08;一&#xff09;代码架构图 &#xff08;二&#xff09;消息被拒 &#xff08;三&#xff09;消息TTL过期 &#xff08;四&#xff09;队列达到最大长度 一、概念 先从概念解释上搞清楚这个定义&#xff0c;死信&…

Spark 3.3.x 读取 HBase 2.x 异常(无法正常连接或读取数据)

无法连接 1. 先检查集群中的 HBase 服务、ZooKeeper 服务是否正常启动&#xff0c;有没有挂掉。 2. Spark 中的 HBase 版本是否与集群一致&#xff0c;代码中的相关包是否导入正确。 3. 连接参数&#xff08;地址、端口&#xff09;是否设置正确&#xff0c;如下所示&#x…

pyqt 制作exe步骤

之前的博客记录 使用pycharmpyqt 编写一个桌面端&#xff08;mac&#xff09;_python开发桌面工具mac_Y_Hungry的博客-CSDN博客 python开发exe程序界面及打包环境配置_Y_Hungry的博客-CSDN博客 1.编写代码 2.打包 pyinstaller -w --add-data "logo.ico;." --add…

Redis常见的数据类型命令

文章目录Redis 常见的数据类型及命令一、常见的NoSQL二、Redis 简介三、key 键的一些操作命令四、Redis的五种基本数据结构1、String&#xff08;字符串&#xff09;介绍常用命令1.1 set/get1.2 append1.3 strlen1.4 setex1.5 mset/mget1.6 setrange/getrange1.7 setnx1.8 incr…