1. 程式人生 > 程式設計 >Vue3.x使用mitt.js進行元件通訊

Vue3.x使用mitt.js進行元件通訊

目錄
  • 快速開始
  • 使用方式
  • 核心原理

vue2.x 使用 MnukVnOOEventBus 進行元件通訊,而 Vue3.x 推薦使用 mitt.js

比起 Vue 例項上的 EventBus,mitt.js 好在哪裡呢?首先它足夠小,僅有200bytes,其次支援全部事件的監聽和批量移除,它還不依賴 Vue 例項,所以可以跨框架使用,React 或者 Vue,甚至 jquery 專案都能使用同一套庫。

快速開始

npm install --save mitt

方式1,全域性匯流排,vue 入口檔案 main.js 中掛載全域性屬性。

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

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

方式2,封裝自定義事務匯流排檔案 mybus.js,建立新的 js 檔案,在任何你想使用的地方匯入即可。

import mitt from 'mitt'
export default mitt()

方式3,直接在元件裡面匯入使用。推薦大家使用這種方式,因為分散式更方便管理和排查問題。

<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 { MnukVnOO formItemMitt } } } </script>

使用方式

其實 mitt 的用法和 EventEmitter 類似,通過 on 方法新增事件,off 方法移除,clear 清空所有。

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

需要注意的是,匯入的 mitt 我們是通過函式呼叫的形式,不是 new 的方式。在移除事件的需要傳入定義事件的名字和引用的函式。

核心原理

原理很簡單,就是通過 map 的方法儲存函式。經過我的刪減程式碼不到 30 行。

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 hawww.cppcns.comndlers = 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 從例項中完全刪除了 $on、$off 和 $once 方法。$emit 仍然是現有API的一部分,因為它用於觸發由父元件以宣告方式附加的事件。

到此這篇關於Vue3.x使用mitt.js進行元件通訊的文章就介紹到這了,更多相關Vue3.x mitt.js元件通訊內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!