官网 https://github.com/developit/mitt

安装 mitt

npm i --save mitt

创建文件 src/emitter.js

import mitt from "mitt";

export default mitt();

mitt 的核心语法

// 创建事件 foo
emitter.emit('foo', { a: 'b' })

// 监听事件 foo
emitter.on('foo', e => console.log('foo', e) )

// 监听所有事件
emitter.on('*', (type, e) => console.log(type, e) )

// 移除事件 foo
emitter.off('foo', onFoo)  // unlisten

// 移除所有事件
emitter.all.clear()

父组件

<script setup lang="ts">
import emitter from "@/emitter.js";
import Child from "./Child.vue";
import { ref, onMounted, onUnmounted } from "vue";

let msg = ref("");

onMounted(() => {
  // 组件加载时 -- 监听自定义事件 child_msg
  emitter.on("child_msg", (e: string) => (msg.value = e));
});

onUnmounted(() => {
  // 组件卸载时 -- 移除自定义事件 child_msg
  emitter.off("child_msg");
});
</script>

<template>
  <p>来自子组件的消息:{{ msg }}</p>
  <Child />
</template>

子组件

<script setup lang="ts">
import emitter from "@/emitter.js";

function sendMsg() {
  // 创建自定义事件 child_msg
  emitter.emit("child_msg", "你好");
}
</script>

<template>
  <button @click="sendMsg">发送消息</button>
</template>

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部