SoFunction
Updated on 2025-04-14

How to use event bus mitt in Vue3

My usage scenario

I encountered such a problem in the project. The page uses keepalive cache, and the data between employee shifts and shifts is related. When I delete a shift, the shifts arranged for the employee are the deleted shifts. Those that have already taken effect will not be affected, but the shifts that have not taken effect will be deleted. If I don't pull back-end data again, I switch from the shift page to the employee shift scheduling page. My front-end scheduling still exists, but the back-end data has been deleted. At this time, the user clicks to delete the schedule, and there will be unfriendly prompts. I need to avoid this situation. This requires the data of the employee schedule list when deleting the shift again.

How to use

Install mitt

npm install mitt

Create an event bus

Create an event bus in your project that you can put it in a separate file, e.g.

// 
import mitt from 'mitt';
export const eventBus = mitt();

Listen to events during employee scheduling

Listen to events from the event bus, and then call the corresponding method. Remember to cancel the listening when the page is destroyed.

// 
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { eventBus } from '@/path/to/eventBus';		// This path needs to correspond to
export default {
  setup() {
    const search = () => {
      // Execute the method here      ('Method is called');
    };

    onMounted(() => {
      ('getScheduleSearch', search);
    });

    // Cancel the listening when the page is destroyed    onBeforeUnmount(() => {
      ('getScheduleSearch', search);
    });

    return {};
  },
};

Trigger event in shift page

Trigger event to notify employees of the execution method of the scheduling page.

// 
import { ref } from 'vue';
import { eventBus } from '@/path/to/eventBus';		// This path needs to correspond to
export default {
  setup() {
  	// Assume this is my way to delete the shift    const deleteShift = () => {
      // Trigger the event here to notify the staff of the execution method of the scheduling page.      ('getScheduleSearch');
    };

    return { getScheduleSearch };
  },
};

This way, when you call the deleteShift method in the shift page, the search method in the employee scheduling page will be triggered. This is a simple and flexible way of communication based on events, suitable for decoupling between different components.

Extension: vue3 mitt for sibling components communication

mitt, also known as transaction bus, is a third-party plug-in.

Use EventBus for component communication, and it is recommended to use .

advantage

First of all, it is small enough, with only 200bytes, and secondly, it supports listening 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 set of libraries.

download

npm install --save mitt

Introduced

Method 1: Global bus

import { createApp } from 'vue';

import App from './';

import mitt from "mitt"

const app = createApp(App)

.$mybus = mitt()

Method 2: Define the file separately and import it when you want to use it.

//documentimport mitt from 'mitt'
const emitter = mitt();
export default emitter ;

Method 3: Import directly in the component

import mitt from 'mitt'

setup(){
 const emitter = mitt();
 return{
emitter
}
}

use

//useimport emitter from '@/utils/';
//send('getDetail',{name:'Zhang San',age:20});
//monitor("getDetail",(val) = >{
(val)
})
//Cancel the monitoring("getDetail")
//If multiple sends, you can listen to all("*",(type,val) = >{
   (type,val)   //type is the type. The previously registered getDetail})
//Cancel all listening();

Core Principle

Removed from the instance later$on$offand$oncemethod,$emitStill part of the existing API, only methods for child components to trigger parent components can be implemented.

The principle is very simple, which is to save the function through map method.

export default function mitt(all) {
 all = all || new Map();
 
 return {
  all,
 
  on(type, handler) {
   const handlers = (type);
   const added = handlers && (handler);
   if (!added) {
    (type, [handler]);
   }
  },
 
  off(type, handler) {
   const handlers = (type);
   if (handlers) {
    ((handler) >>> 0, 1);
   }
  },
 
  emit(type, evt) {
   (((type) || [])).slice().map((handler) => { handler(evt); });
   ((('*') || [])).slice().map((handler) => { handler(type, evt); });
  }
 };
}

This is the article about how to use event bus mitt in Vue3. For more related Vue3 event bus mitt content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!