簡體   English   中英

具有組合 API 的 Vue 3 事件總線

[英]Vue 3 Event Bus with Composition API

我已經設置了手套並嘗試將事件分派給另一個組件,但我很難過,因為在setup()方法中this沒有用於訪問應用程序實例的功能。

這是我嘗試過的:

import App from './App.vue'
const el = document.getElementById('app')

import mitt from 'mitt';
const emitter = mitt();

const app = createApp(App)
app.config.globalProperties.emitter = emitter;
app.mount(el);

在組件中,我想調度一個事件

export default {
   setup() {
      function toggleSidebar() {
          this.emitter.emit('toggle-sidebar');

          console.log(this); // binds to setup(), not the vue instance.
      }
   }
}

由於this不存在,我無法訪問.emitter 我錯過了什么? 如何在 Vue 3 組合 api 中使用官方建議的手套?


順便說一句,如果我使用 v2 語法,我可以訪問this.emitter 但是我很好奇組合API方式

export default {
  mounted() {
    console.log(this.emitter); // works
  }
} 

要在 Vue 3 組合 API 中使用事件總線,請在 main.js 中使用 Vue 3 的新provide api ,然后inject任何組件:

1. 安裝手套

npm install mitt

2. 提供:

main.js

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

import mitt from 'mitt';                  // Import mitt
const emitter = mitt();                   // Initialize mitt

const app = createApp(App);
app.provide('emitter', emitter);          // ✅ Provide as `emitter`
app.mount('#app');

3.注入

3a。 任何組件-發出事件

import { inject } from 'vue'

export default {
  setup() {
    const emitter = inject('emitter'); // Inject `emitter`
    const mymethod = () => {
      emitter.emit('myevent', 100);
    };
    return {
      mymethod
    }
  }
}

通過單擊按鈕或其他方式調用mymethod

3b。 任何組件-監聽事件

import { inject } from 'vue'

export default {
  setup() {
    const emitter = inject('emitter');   // Inject `emitter`

    emitter.on('myevent', (value) => {   // *Listen* for event
      console.log('myevent received!', `value: ${value}`);
    });
  },
}

安慰

myevent received! value: 100 

您也許可以使用getCurrentInstance來獲取全局屬性

零件:

import { getCurrentInstance } from 'vue';
export default {
  setup() {
    // get current instance
    const internalInstance = getCurrentInstance(); 
    // get the emitter from the instance
    const emitter = internalInstance.appContext.config.globalProperties.emitter;
  }
} 

到目前為止,我已經使用此代碼使“發射器”可用。

//main.ts
import mitt from 'mitt'
const emitter = mitt()
export default emitter

然后在我使用的組件內部

import emitter from '@/main';

到目前為止,這在 Vue2 和 Vue3 中有效——至少在選項 API 中有效。

我不得不承認,我目前在使用新的 vite 服務器和熱模塊重載(hmr)時遇到了一些問題。 這種風格在任何方面都不是最理想的嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM