Vue3.x uses mitt.js for component communication

Vue3.x uses mitt.js for component communication

Vue2.x uses EventBus for component communication, while Vue3.x recommends using mitt.js.

How is mitt.js better than EventBus on a Vue instance? First of all, it is small enough, only 200 bytes. Secondly, it supports monitoring and batch removal of all events. It does not rely on Vue instances, so it can be used across frameworks. React or Vue, and even jQuery projects can use the same library.

Quick Start

npm install --save mitt

Method 1, global bus, mount global properties in the vue entry file main.js.

import { createApp } from 'vue';
import App from './App.vue';
import mitt from "mitt"

const app = createApp(App)
app.config.globalProperties.$mybus = mitt()

Method 2: Encapsulate the custom transaction bus file mybus.js, create a new js file, and import it anywhere you want to use it.

import mitt from 'mitt'
export default mitt()

Method 3: Import and use directly in the component. It is recommended that you use this method because the decentralized approach makes management and troubleshooting easier.

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld msg="Hello Vue 3.0 + Vite" />
</template>

<script>
import mitt from 'mitt'
import HelloWorld from './components/HelloWorld.vue'

export default {
  components:
    HelloWorld
  },
  setup (props) {
    const formItemMitt = mitt()
    return {
      formItemMitt
    }
  }
}
</script>

How to use

In fact, the usage of mitt is similar to EventEmitter. Events are added through the on method, removed through the off method, and cleared through the clear method.

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

It should be noted that we imported mitt in the form of function call, not new. When removing an event, you need to pass in the name and reference of the function that defines the event.

Core Principles

The principle is very simple, which is to save the function through the map method. After my deletion, the code is less than 30 lines.

export default function mitt(all) {
 all = all || new Map();

 return {
  all,

  on(type, handler) {
   const handlers = all.get(type);
   const added = handlers && handlers.push(handler);
   if (!added) {
    all.set(type, [handler]);
   }
  },

  off(type, handler) {
   const handlers = all.get(type);
   if (handlers) {
    handlers.splice(handlers.indexOf(handler) >>> 0, 1);
   }
  },

  emit(type, evt) {
   ((all.get(type) || [])).slice().map((handler) => { handler(evt); });
   ((all.get('*') || [])).slice().map((handler) => { handler(type, evt); });
  }
 };
}

Vue3 completely removed the $on, $off, and $once methods from the instance. $emit is still part of the existing API, as it is used to trigger events that are attached declaratively by a parent component.

This is the end of this article about Vue3.x using mitt.js for component communication. For more relevant Vue3.x mitt.js component communication content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of non-parent-child component communication in Vue3
  • Details of 7 kinds of component communication in Vue3
  • Steps for Vue3 to use mitt for component communication
  • Summary and examples of vue3 component communication methods

<<:  Summary of basic knowledge points of Linux group

>>:  How to add indexes to MySQL

Recommend

Beginners learn some HTML tags (3)

Related articles: Beginners learn some HTML tags ...

SQL merge operation of query results of tables with different columns

To query two different tables, you need to merge ...

Detailed introduction to MySQL database index

Table of contents Mind Map Simple understanding E...

How to use CSS counters to beautify ordered lists of numbers

In web design, it is very important to use an org...

Win10 64-bit MySQL8.0 download and installation tutorial diagram

How do I download MySQL from the official website...

Summary of Common Commands for Getting Started with MySQL Database Basics

This article uses examples to describe the common...

HTML tag dl dt dd usage instructions

Basic structure: Copy code The code is as follows:...

5 Easy Ways to Free Up Space on Ubuntu

Preface Most people will probably perform this op...

30 Tips for Writing HTML Code

1. Always close HTML tags In the source code of p...

Windows Server 2019 IIS10.0+PHP(FastCGI)+MySQL Environment Construction Tutorial

Preparation 1. Environmental Description: Operati...

JavaScript implements changing the color of a web page through a slider

Hello everyone, today when I was looking at the H...

Implementation of new issues of CSS3 selectors

Table of contents Basic Selector Extensions Attri...

【HTML element】How to embed images

The img element allows us to embed images in HTML...