带有 Composition API 的 Vue 3 事件总线 [英] Vue 3 Event Bus with Composition API
问题描述
我已经设置了 mitt 并尝试将事件分派到另一个组件,但我很难,因为在 setup()
方法中,它没有用于访问应用程序实例的 this
.
I have setup mitt and trying to dispatch event to another component but I am having hard time because in the setup()
method it doesn't have this
for accessing app instance.
这是我尝试过的:
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);
在组件中,我想调度一个事件
And in the component, I want to dispatch an event
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 中使用官方建议的手套?
As this
doesn't exist, I can't access the .emitter
. What am I missing? How to use officially suggested mitt in Vue 3 composition api?
顺便说一下,如果我使用 v2 语法,我可以访问 this.emitter
.但我对 Composition API 方式很好奇
By the way if I use the v2 syntax, I can access this.emitter
. But I am curious about Composition API way
export default {
mounted() {
console.log(this.emitter); // works
}
}
推荐答案
要在 Vue 3 Composition API 中使用事件总线,请使用 Vue 3 的新 provide
api main.js,然后inject
在任何组件中:
To use an event bus in Vue 3 Composition API, use Vue 3's new provide
api in main.js, and then inject
in any component:
1.安装 mitt:
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
这篇关于带有 Composition API 的 Vue 3 事件总线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!