官网 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. 原创作者: u_15715491 转载于: https://blog.51cto.com/u_15715491/11662553