问题描述
如何在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
和$emit
方法.
In Vue 3, Vue
is not a constructor anymore, and Vue.createApp({});
returns an object that has no $on
and $emit
methods.
推荐答案
如官方文档,您可以使用 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 :
导入该库并创建该发射器的实例,并将其定义为全局属性:
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();
let app=createApp(App)
app.config.globalProperties.emitter = emitter
app.mount('#app')
标头中的
发出带有某些有效负载的toggle-sidebar
事件:
<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>
对于使用composition api的用户,可以按以下方式使用emitter
:
For those using composition api they could use emitter
as follows :
import { getCurrentInstance } from 'vue'
export default{
setup(){
const internalInstance = getCurrentInstance();
const emitter = internalInstance.appContext.config.globalProperties.emitter;
...
},
...
}
这篇关于Vue.js 3事件总线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!