在vue中,父子组件是用的非常频繁的,但是最近项目中,一个页面由左、中、右三个兄弟组件构成,其中,右侧组件点击按钮,需要调用中间组件的保存方法,而且要把选中的数据传到中间组件。我想到的解决办法是事件总线,但是事件总线的常用两种一个是 调事件,另一个是单纯传参数,这时应该怎么做到既在中间组件接收参数,又调用中间组件的保存方法呢?
事件总线的使用 - main.js
EventBus.js中导出:
import { EventEmitter } from 'events';
const EventBus = new EventEmitter();
export default EventBus;
在main.js中引入
……
import EventBus from './utils/EventBus';
……
app.config.globalProperties.$EventBus = EventBus;
解决方案
右侧组件事件中触发事件总线:
this.$EventBus.emit('__save', data);
中间组件接收参数,并在watch里触发保存事件: mounted钩子函数中接收事件总线:
mounted() {
// 【事件总线】
this.$EventBus.on('__save', (data) => {
this.receiveParameters = data;
//receiveParameters为该页面data中定义的
});
},
在watch中监听这个receiveParameters:
watch: {
receiveParameters: {
handler() {
this.onSave();
},
deep: true,
},
},
在中间事件就可以触发保存事件,并拿到右侧组件传来的值了,算是曲线救国:
method: {
onSave(){
console.log('右侧组件传来的数据',this.receiveParameters)
}
}
好了,你们觉得这种办法怎么样呢,其实如果事件总线中既调用事件,又能在事件中获取到传来的参数是最好的办法,但是我不知道怎么实现,有大佬请指教!