前端mitt的使用

mitt与pubsub订阅消息与发布消息功能类似,它可以实现在任意组件间的通信。

1.安装mitt

在终端中输入命令npm i mitt来安装。

2.第2步:在src的文件下新建文件夹utils,然后在utils文件夹中新建文件emitter.ts(必须是.ts结尾的)

//引入mitt插件;mitt是一个方法,执行返回一个bus对象
import mitt from 'mitt'
//调用mitt,得到$bus,$bus可以用来绑定事件和触发事件
const $bus = mitt()
//暴露一下对象
export default $bus

3.在需要接收或发送数据的地方需要引用(注意:暴露的对象名称和引用路径的名称需要一致)

import $bus from '../bus';

     

3.2 $bus基本用法
$bus身上有四个方法,分别是

**on()😗*用来绑定事件,接收两个参数,第一个参数是事件名,第二个参数是事件触发时的回调函数;
**emit()😗*用来触发事件,参数为事件名;
**off()😗*用来解绑事件,参数为事件名;
**all:**all有clear属性,直接调用clear()属性可以解绑全部事件。
如何使用:

<template>
<div class="child1">
<h3>我是子组件1:曹植</h3>
</div>
</template>
<script setup lang="ts">
//接受bus对象
import $bus from "../bus"
//使用组合式Api:vue3
import { onMounted } from "vue";
//组件挂载完毕的时候,当前组件绑定一个事件,接受将来兄弟组件传递的数据
onMounted(() => { 
    //第一个参数:即为事件的类型  第2个参数即位事件的回调函数
    $bus.on('car', (car) => {
        console.log(car);
    });
})


</script>
<style scoped>
.child1{
    width: 300px;
    height: 300px;
    background: hotpink;
}
</style>

    第2步

<template>
    <div class="child2">
        <h2>
            我是子组件2:我是2号
        </h2>
        <button @click="hanldes">给曹植送一辆车</button>
       </div>
</template>
<script>
//引入$bus 对象
import $bus from '../bus';
//点击按钮回调
const hanldes = () => { 
    //发送数据 $bus.emit('事件名称', {发送的数据});
    $bus.emit('car', {car:"法拉利"});

}
</script>
<style scoped>
.child2{
    width: 300px;
    height:300px;
    background:skyblue;
}   
</style>

                mitt类似于全局事件的总线

展示的效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值