Vue3 实现Event-Bus事件总线 (mitt插件)

安装mitt

"mitt": "^3.0.1",

bus.js

import mitt from 'mitt'
const Bus = mitt();
export default Bus
  

a.vue

<template>
  <el-button @click="test">bus</el-button>
</template>
<script setup>
import Bus from "@/bus";
import { onMounted, ref, onBeforeUnmount, onUnmounted } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
const a = ref("我是test页面的值");
function test() {
  Bus.emit("changeMsg", a.value);
  router.push("/bus-b");
}
onBeforeUnmount(() => {
  Bus.emit("changeMsg", a.value);
});
onUnmounted(() => {
  Bus.emit("changeMsg", a.value);
});
</script>

b.vue

<template>
  <div>{{ msg }}</div>
</template>
<script setup>
import Bus from "@/bus";
import { ref, onBeforeUnmount } from "vue";
const msg = ref("");
console.log(
  Bus.on("changeMsg", () => {
    sayHi();
  })
);
function sayHi() {
  msg.value = "hi";
}
onBeforeUnmount(() => {
  Bus.emit("changeMsg", sayHi);
});
</script>


封装的event bus最优使用场景
1、非父子组件之间的通信:
如果需要在非父子关系的组件之间进行通信,可以使用自己封装的 Event Bus 实现跨级通信。

2、多个兄弟组件之间的通信:
如果需要多个兄弟组件之间相互通信,则可以使用自己封装的 Event Bus 来实现。

3、全局事件监听:
如果需要在任何地方都能监听到某个事件并做出响应,则可以使用自己封装的全局事件总线来实现。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容