vue3探索——组件通信之事件总线

Vue2.x使用EventBus进行组件通信,而Vue3.x推荐使用mitt.js

比起Vue实例上的EventBusmitt.js好在哪里呢?首先它足够小,仅有200bytes,其次支持全部事件的监听和批量移除,它还不依赖Vue实例,所以可以跨框架使用,React或者Vue,甚至jQuery项目都能使用同一套库。

安装

  • 使用yarn安装
yarn add mitt
  • 或者通过npm安装
npm install --save mitt

官方使用案例

import mitt from 'mitt'

const emitter = mitt()

// listen to an event
emitter.on('foo', e => console.log('foo', e) )

// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )

// fire an event
emitter.emit('foo', { a: 'b' })

// clearing all events
emitter.all.clear()

// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo)   // listen
emitter.off('foo', onFoo)  // unlisten

示例

  • 可以封装一个ES模块,对外暴露一个mitt实例
// src/common/bus.js

// 引入mitt插件
import mitt from 'mitt';
const $bus = mitt();
export default $bus;
  • 挂载到Vue全局变量上
// src/main.ts

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'

import $bus from './bus/index.ts'

const app = createApp(App);
app.config.globalProperties.$bus = $bus;

app.mount('#app');
  • 在父组件中使用
// src/App.vue

<template>
  <div>
    <button @click="giveMoney(200)">打钱</button>
    <Son></Son>
  </div>
</template>

<script lang="ts" setup>
import Son from './components/son.vue';
import { getCurrentInstance } from 'vue';

const { proxy }: any = getCurrentInstance();
const $bus = proxy.$bus;

function giveMoney(num: number) {
	// 通过emit方法触发
  $bus.emit('add', num);
}
</script>
  • 在子组件中使用
// src/components/son.vue

<template>
    <div>
        <h2>I am son</h2>
        <p>我收到了{{ money || 0 }}¥</p>
    </div>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance } from 'vue';

const { proxy }: any = getCurrentInstance();
const $bus = proxy.$bus;

const money = ref(0);

// 通过on方法监听
$bus.on('add', (number: number) => {
    // console.log(number);
    money.value = number;
});
</script>
  • 移除事件
// src/App.vue

<button @click="$bus.off('add')">卸载bus总线</button>
<button @click="$bus.all.clear()">卸载所有bus总线</button>
posted @ 2023-08-19 14:33  前端cry  阅读(320)  评论(1编辑  收藏  举报