Vue3使用mitt進行組件通訊

  • Vue2.x使用EventBus進行組件通訊,而Vue3.x推薦使用mitt.js
  • 比起Vue實例上的EventBusmitt.js好在哪裏呢?首先它足夠小,僅有200bytes,其次支持所有事件的監聽和批量移除,它還不依賴Vue實例,因此能夠跨框架使用,React或者Vue,甚至jQuery項目都能使用同一套庫。

1. 安裝

  • 推薦使用yarn安裝(用過都知道有多絲滑)
yarn add mitt
複製代碼
  • 或者經過npm安裝
npm install --save mitt
複製代碼

2. 引入到項目並掛載

  • 能夠在main.js掛載到全局
// 標準的ES模塊化引入方式
import mitt from 'mitt'

const app = createApp(App)

// vue3.x的全局實例,要掛載在config.globalProperties上
app.config.globalProperties.$EventBus = new mitt()
複製代碼
  • /common/EventBus.js:也能夠封裝一個ES模塊,對外暴露一個Mitt實例
import mitt from 'mitt'
export default new mitt()
複製代碼
  • /views/Home.vue:業務模塊引入來使用
import EventBus from '/common/EventBus.js'
複製代碼

3. 使用

  • 經過on監聽/emit觸發
/* * App.vue */
// setup中沒有this,須要經過getCurrentInstance來獲取Vue實例
import { getCurrentInstance } from 'vue'
import { Mp3Player } from '/common/Mp3Player.js'

export default {
  setup(){
    // ctx等同於Vue2.x的this
    const { ctx } = getCurrentInstance()
    
    // 監聽-若是有新任務則播放音效
    ctx.$EventBus.on('newTask', data => {
      Mp3Player.play()
    })

    // 也能夠經過*監聽全部任務
    ctx.$EventBus.on('*', data => {
      console.log('EventBus come in', data)
    })
  }
}


/* * Control.vue */
// 判斷有新任務時,觸發
ctx.$EventBus.emit('newTask', data)
複製代碼
  • off移除事件
import {
    onBeforeUnmount,
    getCurrentInstance
  } from 'vue'

export default {
  setup(){
    const { ctx } = getCurrentInstance()

    onBeforeUnmount(() => {
      // 移除指定事件
      ctx.$EventBus.off('newTask')

      // 移除所有事件
      ctx.$EventBus.all.clear()
    })
  }
}
複製代碼

參考

相關文章
相關標籤/搜索