介绍
- Vue3移除了$on $off等自带的自定义事件相关方法,因此在vue3中他推荐我们下载mitt库来使用事件总线传递数据
安装
npm install mitt
使用
1. 定义一个工具库
src/bus/index.ts
//引入mitt插件:mitt一个方法,方法执行会返回bus对象
import mitt from 'mitt';
const $bus = mitt();
export default $bus;
2.组件中使用
假设Child1 和 Child2 是兄弟组件,2需要给1传过去一辆车的信息可以这样定义
接收方(Child1):
<template>
<div class="child1">
<h3>我是子组件1:曹植</h3>
</div>
</template>
<script setup lang="ts">
import $bus from "../../bus";
//组合式API函数
import {
onMounted } from "vue";
//组件挂载完毕的时候,当前组件绑定一个事件,接受将来兄弟组件传递的数据
onMounted(() => {
//第一个参数:即为事件类型 第二个参数:即为事件回调
$bus.on("car", (car) => {
console.log(car);
});
});
</script>
<style scoped>
.child1 {
width: 300px;
height: 300px;
background: hotpink;
}
</style>
传送方(Child2):
<template>
<div class="child2">
<h2>我是子组件2:曹丕</h2>
<button @click="handler">点击我给兄弟送一台法拉利</button>
</div>
</template>
<script setup lang="ts">
//引入$bus对象
import $bus from '../../bus';
//点击按钮回调
const handler = ()=>{
$bus.emit('car',{
car:"法拉利"});
}
</script>
<style scoped>
.child2{
width: 300px;
height: 300px;
background: skyblue;
}
</style>
演示结果
Vue3通过mitt实现全局事件总线