Vue.js 3 事件总线 [英] Vue.js 3 Event Bus
问题描述
如何在 Vue 3 中创建事件总线?
How to create Event Bus in Vue 3?
在 Vue 2 中,它是:
In Vue 2, it was:
export const bus = new Vue();
bus.$on(...)
bus.$emit(...)
在 Vue 3 中,Vue
不再是构造函数,并且 Vue.createApp({});
返回一个没有 $on
的对象code> 和 $emit
方法.
In Vue 3, Vue
is not a constructor anymore, and Vue.createApp({});
returns an object that has no $on
and $emit
methods.
推荐答案
如官方建议的 docs 你可以使用 mitt 库在组件之间调度事件,让假设我们有一个侧边栏和 header
,其中包含一个关闭/打开侧边栏的按钮,我们需要该按钮来切换侧边栏组件内的某些属性:
As suggested in official docs you could use mitt library to dispatch events between components, let suppose that we a sidebar and header
which contains a button that close/open the sidebar and we need that button to toggle some property inside the sidebar component :
在 main.js 中导入该库并创建该发射器的实例并将其定义为 全局属性:
in main.js import that library and create an instance of that emitter and define as a global property:
安装:
npm install --save mitt
用法:
import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt';
const emitter = mitt();
const app = createApp(App);
app.config.globalProperties.emitter = emitter;
app.mount('#app');
在标题中发出带有一些负载的 toggle-sidebar
事件:
in header emit the toggle-sidebar
event with some payload :
<template>
<header>
<button @click="toggleSidebar"/>toggle</button>
</header>
</template>
<script >
export default {
data() {
return {
sidebarOpen: true
};
},
methods: {
toggleSidebar() {
this.sidebarOpen = !this.sidebarOpen;
this.emitter.emit("toggle-sidebar", this.sidebarOpen);
}
}
};
</script>
在侧边栏中接收带有有效负载的事件:
In sidebar receive the event with the payload:
<template>
<aside class="sidebar" :class="{'sidebar--toggled': !isOpen}">
....
</aside>
</template>
<script>
export default {
name: "sidebar",
data() {
return {
isOpen: true
};
},
mounted() {
this.emitter.on("toggle-sidebar", isOpen => {
this.isOpen = isOpen;
});
}
};
</script>
对于那些使用组合 API 的人,他们可以使用 emitter
如下:
For those using composition api they could use emitter
as follows :
创建一个文件 src/composables/useEmitter.js
Create a file src/composables/useEmitter.js
import { getCurrentInstance } from 'vue'
export default function useEmitter() {
const internalInstance = getCurrentInstance();
const emitter = internalInstance.appContext.config.globalProperties.emitter;
return emitter;
}
从那以后,您可以像使用 useRouter
一样使用 useEmitter
:
And from there on you can use useEmitter
just like you would with useRouter
:
import useEmitter from '@/composables/useEmitter'
export default {
setup() {
const emitter = useEmitter()
...
}
...
}
这篇关于Vue.js 3 事件总线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!