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 本质也是一种回调函数。

相关推荐
若惜9 分钟前
selenium自动化测试web自动化测试 框架封装Pom
前端·python·selenium
Amumu1213822 分钟前
Js:内置对象
开发语言·前端·javascript
广州华水科技24 分钟前
2026年单北斗GNSS变形监测系统推荐,助力精准监控与智慧城市建设
前端
鸡吃丸子28 分钟前
如何编写一个高质量的AI Skill
前端·ai
我命由我1234539 分钟前
Element Plus 2.2.27 的单选框 Radio 组件,选中一个选项后,全部选项都变为选中状态
开发语言·前端·javascript·html·ecmascript·html5·js
Luna-player41 分钟前
第3章 Spring Boot的Web应用支持,个人学习笔记
前端·spring boot·学习
bugcome_com42 分钟前
【ASP.NET Web Pages】页面布局核心实战:从复用性到安全性,打造一致化网站界面
前端·后端·asp.net
Sylus_sui42 分钟前
Class 模型 + 跨组件状态(@Observed)+ 网络请求封装 + 本地存储全部是鸿蒙 Next/Stage 模型标准写法
前端
代码栈上的思考1 小时前
消息队列持久化:文件存储设计与实现全解析
java·前端·算法
踩着两条虫1 小时前
去“AI味儿”实操手册:从“机器脸”到“高级脸”,只差这三步!
前端·vue.js·ai编程