当前位置: 首页 > backend >正文

Vue3组件通信 emit 的工作原理

文章目录

  • 前言
    • 🔧 使用方式简述
    • ⚙️ 源码角度解析 `emit`
      • 一、组件实例初始化时的 `emit`
      • 二、emit 函数的定义
      • 三、关键点说明
    • 🧠 总结流程图(简化)
    • 🔍 结合运行时举个实际例子
    • 📌 总结


前言

Vue 3 中 emit 是组件之间通信的重要机制,通常用于 子组件向父组件发送事件。下面我们结合源码,深入理解 emit 的工作原理。


🔧 使用方式简述

子组件中:

defineProps(['msg'])
const emit = defineEmits(['change'])function triggerChange() {emit('change', 'new value')
}

父组件中:

<MyComponent @change="onChange" />

⚙️ 源码角度解析 emit

Vue 3 中的 emit 是在 组件实例 (ComponentInternalInstance) 的上下文中定义的函数。它的实现主要在 Vue 3 的核心包 @vue/runtime-core 中。

一、组件实例初始化时的 emit

位于:packages/runtime-core/src/component.ts

export function createComponentInstance(...) {const instance: ComponentInternalInstance = {...emit: (...args) => {emit(instance, ...args)}}...
}

这里 emit 是一个闭包,它绑定了当前组件实例,最终调用了 emit(instance, ...args) 这个方法。


二、emit 函数的定义

位于:packages/runtime-core/src/componentEmits.ts

export function emit(instance: ComponentInternalInstance,event: string,...rawArgs: unknown[]
) {const props = instance.vnode.props || EMPTY_OBJlet handlerName = toHandlerKey(event) // 比如 'change' => 'onChange'let handler = props[handlerName]if (!handler && event.toLowerCase() !== event) {handler = props[handlerName.toLowerCase()]}if (handler) {callWithAsyncErrorHandling(handler, instance, ErrorCodes.COMPONENT_EVENT_HANDLER, args)}
}

三、关键点说明

步骤内容
toHandlerKey('change')会变成 onChange,这是 Vue 事件绑定的内部规则
props.onChange从组件的 vnode.props 上查找对应的事件处理函数
callWithAsyncErrorHandling调用函数时,带有错误处理机制(防止 UI 崩溃)

🧠 总结流程图(简化)

emit('change', value)↓
组件内部的 emit 实例函数↓
调用 @vue/runtime-core 的 emit(instance, 'change', value)↓
查找 props 中的 onChange↓
找到后执行 onChange(value)

🔍 结合运行时举个实际例子

const emit = defineEmits(['submit'])function onClick() {emit('submit', { name: 'Vue' })
}

编译后模板中,父组件绑定的是 onSubmit

<Child @submit="handleSubmit" />

Vue 会在创建 VNode 时把 @submit="handleSubmit" 转成:

props: {onSubmit: handleSubmit
}

然后通过上面提到的 emit 源码逻辑找到 onSubmit 并执行。


📌 总结

  • Vue 3 中的 emit 是通过组件实例绑定的 emit 函数实现的;
  • 实际调用的是 runtime-core 中的 emit(instance, eventName, ...args)
  • emit 会根据事件名(如 change)生成 onChange 并在 props 中查找是否有对应函数;
  • callWithAsyncErrorHandling 确保事件处理函数执行时出错不会影响整个应用。

http://www.xdnf.cn/news/5306.html

相关文章:

  • 真人配音与AI创作有声读物
  • 操作系统学习笔记第1章 (竟成)
  • List接口
  • C PRIMER PLUS——第7节:指针
  • Day 3:Warp协作功能深度实战
  • 运放OP方向技术要点和大厂题目解析
  • 文件IO之系统IO
  • dockerfile编写入门
  • 十六、统一建模语言 UML
  • 16前端项目----交易页
  • QT6 源(90):阅读与注释 LCD显示类 QLCDNumber ,源代码以及属性测试。该类继承于容器框架 QFrame
  • Windows报错:OSError: [WinError 1455] 页面文件太小,无法完成操作的问题
  • Redis能保证数据不丢失吗之RDB
  • 【Web】使用Vue3开发鸿蒙的HelloWorld!
  • 模拟太阳系(C#编写的maui跨平台项目源码)
  • Autoware message_filters::Synchronizer链接错误问题
  • Axure疑难杂症:统计分析页面引入Echarts示例动态效果
  • 目录粘滞位的使用
  • JDBC链接数据库
  • 【typenum】 0 配置文件(Cargo.toml)
  • 【MySQL】事务(重点)
  • 酒店洗护用品那些事儿:品牌选择及扬州卓韵用品介绍
  • 6. 存储池配置与CephFS创建 ceph version 14.2.22
  • muduo源码解析
  • 【第33节 数据库基础概念】
  • 游戏引擎学习第269天:清理菜单绘制
  • [模型选择与调优]机器学习-part4
  • PyTorch API 6 - 编译、fft、fx、函数转换、调试、符号追踪
  • HTTP 请求中 Content-Type 头部
  • 使用谱聚类将相似度矩阵分为2类