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

相关推荐
LYFlied3 分钟前
从 Vue 到 React,再到 React Native:资深前端开发者的平滑过渡指南
vue.js·react native·react.js
爱喝白开水a18 分钟前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌4119 分钟前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
B站_计算机毕业设计之家33 分钟前
豆瓣电影数据采集分析推荐系统 | Python Vue Flask框架 LSTM Echarts多技术融合开发 毕业设计源码 计算机
vue.js·python·机器学习·flask·echarts·lstm·推荐算法
吃杠碰小鸡1 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone1 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_09012 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农2 小时前
Vue 2.3
前端·javascript·vue.js
夜郎king2 小时前
HTML5 SVG 实现日出日落动画与实时天气可视化
前端·html5·svg 日出日落
跳动的梦想家h3 小时前
环境配置 + AI 提效双管齐下
java·vue.js·spring