组件通信方式之全局事件总线–mitt
直接上代码ba
引入mitt
并创建实例
//引入mitt插件:mitt一个方法,方法执行会返回bus对象
import mitt from "mitt";
//npm官方文档 https://www.npmjs.com/package/mitt
// 创建mitt实例
const $bus = mitt();
export default $bus;
父组件代码EventBusTestM.vue
<script setup lang="ts">
import Child1 from "./Child1M.vue";
import Child2 from "./Child2M.vue";
</script>
<template>
<div class="container">
<h1>全局事件总线$bus</h1>
<hr />
<div class="child">
<Child1></Child1>
<Child2></Child2>
</div>
</div>
</template>
<style scoped>
.container {
width: 100vw;
height: 400px;
background: yellowgreen;
}
.child {
display: flex;
justify-content: space-between;
}
</style>
子组件1代码Child1.vue
<script setup lang="ts">
import { onMounted } from "vue";
import $bus from "../../bus";
onMounted(() => {
// 绑定事件,两个参数:name:绑定的方法名,callback:触发后执行的回调函数
$bus.on("car", (car) => {
console.log(car);
});
});
</script>
<template>
<div class="child1">
<h1>我是Child1组件</h1>
</div>
</template>
<style scoped>
.child1 {
width: 300px;
height: 300px;
background: hotpink;
}
</style>
子组件2代码Child2.vue
<script setup lang="ts">
import $bus from "../../bus";
const handler2 = () => {
//触发事件,两个参数:name:触发的方法名,data:需要传递的参数
$bus.emit("car", { car: "兰博基尼", color: "pink" });
};
</script>
<template>
<div class="child2">
<h1>我是Child2组件</h1>
<button @click="handler2">我想送姐姐一台兰博基尼</button>
</div>
</template>
<style scoped>
.child2 {
width: 300px;
height: 300px;
background: skyblue;
}
</style>
总结:
1.mitt使用逻辑:创建事件对象-发送事件-监听事件
2.发送事件
$bus.emit("car", { car: "兰博基尼", color: "pink" });
监听事件
$bus.on("car", (car) => {
console.log(car);
});
监听所有事件
$bus.on("*", (type, car) => {
console.log(type, car);
});
移除监听事件
$bus.off("car")
清空所有监听事件
$bus.all.clear()
如有错误,欢迎指出,我修正!谢谢!