学习优先度:★★★★☆
难易度:★★★☆☆
Vue.js 中的事件总线允许非父子组件通过发射和监听事件来相互通信。
事件总线是一个简单的 Vue 实例,可用于发射和监听事件,从而促进同级组件或其他不相关组件之间的通信。
【代码示例】
// Step 1: Create the event bus
// eventBus.js
import Vue from 'vue';
export const eventBus = new Vue();
// Step 2: Emit an event from one component
// ComponentA.vue
<template>
<button @click="sendEvent">Send Event</button>
</template>
<script>
import { eventBus } from './eventBus';
export default {
methods: {
sendEvent() {
eventBus.$emit('myEvent', 'Hello from ComponentA');
}
}
}
</script>
// Step 3: Listen for the event in another component
// ComponentB.vue
<template>
<div>{{ message }}</div>
</template>
<script>
import { eventBus } from './eventBus';
export default {
data() {
return {
message: ''
};
},
created() {
eventBus.$on('myEvent', (data) => {
this.message = data;
});
}
}
</script>
【执行结果】
当点击 ComponentA 中的按钮时,ComponentB 中将显示 "Hello from ComponentA"。
事件总线的工作原理是创建一个新的 Vue 实例,并使用其 $emit 和 $on 方法分别发射和监听事件。这种方法简单明了,但应谨慎使用,因为它会给大型应用程序的维护带来挑战。现代 Vue 应用程序可能更喜欢使用 Vuex 或其他状态管理解决方案,以获得更好的可扩展性。
【补充】
Vue 3 引入了 Composition API,它还可以通过反应对象和反射促进组件通信,提供了一种更具可扩展性和可维护性的方法。