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

Front-end state management (Part 1)

Table of contents 1. What is front-end state mana...

Introduction to possible problems after installing Tomcat

1. Tomcat service is not open Enter localhost:808...

How to solve the problem of blurry small icons on mobile devices

Preface Previously, I talked about the problem of...

Implementation of tomcat deployment project and integration with IDEA

Table of contents 3 ways to deploy projects with ...

Mysql implements three functions for field splicing

When exporting data to operations, it is inevitab...

CocosCreator learning modular script

Cocos Creator modular script Cocos Creator allows...

Mysql uses insert to insert multiple records to add data in batches

If you want to insert 5 records into table1, the ...

How to implement checkbox & radio alignment

Not only do different browsers behave differently...

Implementation process of row_number in MySQL

1. Background Generally, in a data warehouse envi...

How to modify the ssh port number in Centos8 environment

Table of contents Preface start Preface The defau...

How to set default value for datetime type in MySQL

I encountered a problem when modifying the defaul...

js implements form validation function

This article example shares the specific code of ...

Three commonly used MySQL data types

Defining the type of data fields in MySQL is very...

Detailed explanation of ActiveMQ deployment method in Linux environment

This article describes the deployment method of A...