第 363 篇 · 第 14 卷 前端,沒有極限 2026 年 7 月 16 日 · 台北
ls -lt ./posts --since=2013 REC · node 363 · uplink

development

Vue3 中使用 Event Bus

2020 年 12 月 15 日 · 2 分鐘閱讀 · By Wang Casper

Vue 2 中要進行跨元件通訊,除了 Vuex 以外的另一個常見手法是 Event Bus,對於小型專案來說 Event Bus 相當方便,僅需要 $on$emit 兩個語法就能進行跨元件通訊。而 Vue 3 中移除了 $on$off 等語法,因此 Event Bus 也等同於被移除。

在 Vue 3 的官方文件中也有提如果有類似的功能需求,可以參考相關的套件 mitttiny-emitter,兩者運作上差異不大,在此就針對 mitt 來進行介紹。

mitt

mitt 套件可用於 Vue 3,但不僅限於在 Vue 應用中使用,當有跨模組的溝通功能時都可以引用此套件,優點是寫法及運用上都會與 Vue 2 的 Event bus 相當接近(而且不需要在 Vue 的 Prototype 上加入額外的方法)。

mitt: https://github.com/developit/mitt

可愛的拳頭

範例程式碼:

  1. 匯入 mitt 的元件並調用它。
const emitter = mitt();
  1. 建立 HTML 結構,並且加入兩個元件,本範例中會將 component-a 的資料傳送至 component-b
<div id="app">
  <component-a></component-a>
  <hr>
  <component-b></component-b>
</div>
  1. 元件 component-a,會使用 emitter.emit 的方法推送資料至另一個元件上。
app.component('component-a', {
  data() {
    return {
      text: '這有一段話'
    }
  },
  template: `<div>{{ text }} <button type="button" @click="pushData">發送至另一個元件</button></div>`,
  methods: {
    pushData() {
      emitter.emit('getData', this.text);
    }
  }
});
  1. component-b 製作監聽,使用 emitter.on 接收來自於 component-a 的資料。
app.component('component-b', {
  data() {
    return {
      text: '原始資料'
    }
  },
  template: `<div>{{ text }}</div>`,
  created() {
    emitter.on('getData', (msg) => {
      this.text = msg;
    });
  }
});

完整範例

See the Pen Vue 3.x 使用 Event Bus by Wcc723 (@Wcc723) on CodePen.

可點擊畫面中的 「發送至另一個元件」,component-a 的 text 將會透過事件 getData 傳遞至 component-b