Vue组件通信mitt使用

196 阅读1分钟

简介

这个组件用于解决组件之间通信的问题,包括兄弟组件。

使用方式

官方链接

官方介绍

可以看到主要使用的是emiton

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

实际使用

创建消息总线bus

bus.ts

// mitt
import mitt from 'mitt'
// Emitter
const emitter = mitt()
export default emitter

A组件中发送事件

也可以携带参数,参考上面的用法

import emitter from '@/utils/bus'
emitter.emit('submitEyeSeeForm')

B组件中接收事件

import emitter from '@/utils/bus'
emitter.on('submitEyeSeeForm', () => {
    // do something
  })

注意点

需要注意的是,要从同一个地方引入mitt,例如上面都是从bus.ts里面引入的,否则会导致发送的消息接收不到的情况