eventBus使用及其注意事项

时间:2021-04-30 21:13:56   收藏:0   阅读:21

兄弟组件之间的传值,可以用eventBus。

使用步骤

1. 创建一个新的文件,即创建一个新的vue实例。

1 import Vue from ‘vue‘
2 export default new Vue()

2.在要发出数据的组件中

1 import eventBus from ‘@/utils/eventBus.js‘
2 ...
3 destroyed () {
4     eventBus.$emit(‘myFn‘, this.file)//myFn是自定义的函数,第二个参数是需要发出的数据
5 }

注意:最好是在destroyed这个钩子函数中去发出数据,不然拿不到发出的数据。因为路由切换的钩子函数执行顺序是:beforecreated-->created-->beforeMounted-->beforeDestroy-->destroyed-->mounted。在$emit的时候需要已经$on了,才可以监听到。所以最好是在created中$on,在destroyed中$emit。

3.在要接收数据的组件中

1 import eventBus from ‘@/utils/eventBus‘
2 ...
3 created () {
4     eventBus.$on(‘myFn‘, file => {
5     this.file = file
6     })
7 }
8 //file这个形参即为传递过来的数据

 

原文:https://www.cnblogs.com/chenzejie6030/p/14721821.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!