EventBus 是一种简单的事件总线,可以在任何组件中使用。它通过创建一个空的 Vue 实例来实现组件之间的通信。
EventBus:jsCopy
import Vue from 'vue';
export default new Vue();
父组件:htmlCopy
<template>
<div>
<child-component></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
import EventBus from './EventBus';
export default {
components: {
ChildComponent,
},
methods: {
handleClick() {
EventBus.$emit('customEvent', 'Hello from parent!');
},
},
};
</script>
子组件:htmlCopy
<template>
<div>
<button @click="handleClick">Trigger Custom Event</button>
</div>
</template>
<script>
import EventBus from './EventBus';
export default {
methods: {
handleClick() {
EventBus.$emit('customEvent', 'Hello from child!');
},
},
created() {
EventBus.$on('customEvent', data => {
console.log(data);
});
},
};
</script>