Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

When looking at Vue3’s communication methods today, I found a small library recommended: github.com/developit/m… , 119 line | volume is ~ 200 b,. Also exposed four interface API, simple and practical.

We all know that Bus bus-EventBus is used for component communication in Vue2, while MITT is recommended in Vue3

Since it is recommended to use, and so “simple “(small and beautiful), let’s see how to use it

Mitt Usage:

  • Mitt source repository: github.com/developit/m…
  • NPM package address: npmjs.com/package/mit…

NPM install mitt

$ npm install --save mitt
Copy the code

The introduction of

// using ES6 modules
import mitt from 'mitt'

// using CommonJS modules
var mitt = require('mitt')

<script src="https://unpkg.com/mitt/dist/mitt.umd.js"></script>
Copy the code

Three ways to use it

  1. Global bus:Vue main.jsRegister globally
  2. likeVue2Let’s encapsulate a custom bus.
  3. Import and use directly in components (recommended)

use

$on/$off/$once method is removed from Vue3. ~

The usage of mitt is similar to EventEmitter. On method adds events, off method removes, and clear clears everything.

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(The '*'.(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
Copy the code

all

Mapping of event names to registered handler functions.

on

Registers an event handler for a given type.

  • Parameters of the Parameters

  • Type (string | symbol) to listen for the event type or ‘*’ for all events

  • The handler function is called in response to a given event

off

Deletes the event handler for the given type. If handler is omitted, all handlers of a given type are deleted.

Parameters of the Parameters

  • Type (string) | symbolsHandler of the event type to be unregistered, or ‘*’
  • handler FunctionThe handler function to delete

emit

Calls all handlers of the given type. If present, ‘*’ calls the handler after the type matching handler.

Note: Manual triggering of the “*” handler is not supported.

Parameters of the Parameters

  • type ( string | symbol )The type of event to invoke
  • evtAny? Any value (objects are recommended and powerful), passed to each handler

Reference:

  • Mitt source: github.com/developit/m…
  • Mitt package address: npmjs.com/package/mit…