Vue3 implements global event bus through mitt

introduce

  • Vue3 removed custom event-related methods such as $on $off, so in vue3 he recommended us to download the mitt library to use the event bus to transfer data

Install

npm install mitt

use

1. Define a tool library

src/bus/index.ts

//引入mitt插件:mitt一个方法,方法执行会返回bus对象
import mitt from 'mitt';
const $bus = mitt();
export default $bus;

2. Used in components

假设Child1 和 Child2 是兄弟组件,2需要给1传过去一辆车的信息可以这样定义

Receiver (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>

Sender (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>

demo results

Vue3 implements global event bus through mitt

Guess you like

Origin blog.csdn.net/m0_59757074/article/details/131308260