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

相关推荐
佛系打工仔2 小时前
绘制K线第二章:背景网格绘制
android·前端·架构
计算机毕设VX:Fegn08954 小时前
计算机毕业设计|基于springboot + vue医院设备管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
明天好,会的4 小时前
分形生成实验(五):人机协同破局--30万token揭示Actix-web状态管理的微妙边界
运维·服务器·前端
C_心欲无痕4 小时前
nginx - alias 和 root 的区别详解
运维·前端·nginx
北辰alk4 小时前
Vue 路由信息获取全攻略:8 种方法深度解析
vue.js
北辰alk4 小时前
Vue 三剑客:组件、插件、插槽的深度辨析
vue.js
北辰alk5 小时前
Vue Watch 立即执行:5 种初始化调用方案全解析
vue.js
北辰alk5 小时前
Vue 组件模板的 7 种定义方式:从基础到高级的完整指南
vue.js
北辰alk5 小时前
深入理解 Vue 生命周期:created 与 mounted 的核心差异与实战指南
vue.js