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

安装 mitt

npm i --save mitt
  • 1.

创建文件 src/emitter.js

import mitt from "mitt";

export default mitt();
  • 1.
  • 2.
  • 3.

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()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

父组件

<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>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

子组件

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

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

<template>
  <button @click="sendMsg">发送消息</button>
</template>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.