Vue之如何获取自定义事件返回值

在 Vue 中,我们常通过 emit 自定义事件实现父子组件通信(子组件触发事件、父组件监听),也可借助 eventBus 事件总线完成任意组件间的通信。

实际开发中,有时需要获取自定义事件的执行结果,以推进后续逻辑处理。但 emit 本身无返回值,且事件监听函数可能包含异步逻辑,该如何将执行结果回传给触发事件的组件呢?

下文将说明 emit 自定义事件在同步、异步逻辑下的返回值获取方式,eventBus 事件总线的处理方式可参考此逻辑。

一、同步逻辑

子组件触发事件,父组件以同步逻辑处理。

结论:通过回调函数获取到执行结果。

父组件:

js 复制代码
<template>
  <ChildComponent @childEvent="handleChildEvent" />
</template>

<script setup>
import ChildComponent from "./ChildComponent.vue";

function handleChildEvent(callback) {
  const result = "Data from Parent";
  callback(result);
}
</script>

子组件:

js 复制代码
<template>
  <el-button type="primary" @click="triggerEvent"
    >Trigger Child Event</el-button
  >
</template>

<script setup>
const emit = defineEmits(["childEvent"]);
function triggerEvent() {
  emit("childEvent", (result) => {
    console.log("parent result:  ", result);
    // 继续子组件中的逻辑
    // ......
  });
}
</script>

一、异步逻辑

子组件触发事件,父组件以异步逻辑处理。

结论:通过Promise对象拿到执行结果。

父组件:

js 复制代码
<template>
  <ChildComponent @childEvent="handleChildEvent" />
</template>

<script setup>
import ChildComponent from "./ChildComponent.vue";

function otherLogic() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Data from Parent");
    }, 2000);
  });
}
async function handleChildEvent({ resolve, reject }) {
  const result = await otherLogic();
  resolve(result);
}
</script>

子组件:

js 复制代码
<template>
  <el-button type="primary" @click="triggerEvent"
    >Trigger Child Event</el-button
  >
</template>

<script setup>
const emit = defineEmits(["childEvent"]);
async function triggerEvent() {
  try {
    const result = await new Promise((resolve, reject) => {
      emit("childEvent", { resolve, reject });
    });
    console.log("parent result:  ", result);
  } catch (e) {
    console.log(e);
  }
}
</script>

总结

无论是同步还是异步逻辑,本质都是通过回调函数的方式,将父组件(或其他组件)的执行结果回传,而 resolve 本质也是一种回调函数。

相关推荐
数据掘金7 分钟前
百度统计后台页面数据异常?从手动调用时机开始排查
前端
hunteritself8 分钟前
10 层 4K 实时剪辑,国产工作站进入广电制作核心
大数据·前端·人工智能·深度学习·transformer
踩着两条虫9 分钟前
我在浏览器里“盖”了一个村:Vue + Three.js 大屏开发踩坑记
前端·vue.js·three.js
mbshqqb14 分钟前
TypeScript基础教程之同步生成器
前端·javascript·typescript
嘟嘟同学和妮妮同学33 分钟前
【升级】一个中国历史可视化站:皇帝时间线梳理、古代思想流派、诗词鉴赏 (2)
前端·html
暗夜行者之光1 小时前
LangGraph + MCP 实战:构建"自然语言查数据"的 ChatBI Agent
前端·后端
一tiao咸鱼1 小时前
还在手动海投?我做了个 AI 求职助手,自动筛选 BOSS 职位再精准投递
前端·后端·面试
尤水就下1 小时前
🔥预热:在线文档的 block 架构是如何实现的(未完待续...)
前端·javascript·架构
全栈项目管理程序猿1 小时前
ArcGIS JS 基础教程(29):CSVLayer 表格点位图层
前端·javascript
高级程序源2 小时前
SSM仓储管理系统31582-计算机课程设计、毕业设计
vue.js·python·mysql·小程序·flask·课程设计