官网 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>
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » vue3 【自定义事件】mitt 实用教程 (可用于跨组件通信)
发表评论 取消回复