EventBus 是一种常用的方式来实现组件之间的通信。以下是具体步骤:
-
创建 EventBus
在
main.js中创建并挂载EventBus:javascriptCopy Code // main.js import Vue from 'vue'; import App from './App.vue'; export const EventBus = new Vue(); Vue.prototype.$eventBus = EventBus; new Vue({ render: h => h(App), }).$mount('#app'); -
触发事件
在发送事件的组件中,使用
this.$eventBus.$emit触发事件:// SenderComponent.vue export default { methods: { triggerEvent() { this.$eventBus.$emit('deptReset'); } } }; -
监听事件
在接收事件的组件中,使用
this.$eventBus.$on监听事件:export default { created() { // 注意点,这里写法容易出现犯错的情况,必须按照写法一的方式或写法二的方式,如果写成 // 错误写法,这里执行方法多了个括号会引起this指向问题 // this.$eventBus.$on('deptReset', this.handleDeptReset()); // 写法一 this.$eventBus.$on('deptReset', this.handleDeptReset); // 写法二 this.$eventBus.$on('deptReset', ()=>{ this.handleDeptReset() }); }, beforeDestroy() { this.$eventBus.$off('deptReset'); }, methods: { handleDeptReset() { // 执行所需操作 } } };