组件通信方式之全局事件总线

组件通信方式之全局事件总线–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() 

如有错误,欢迎指出,我修正!谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值