在不用Vuex的情况下,当需要做同级组件间的数据传递时我们常常用到EventBus,其实际上就是另外定义一个全局Vue实例,在此实例上订阅和触发事件可以在全局有效。
目前网上的写法大都如此:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| Vue.prototype.$bus = new Vue(); new Vue({ el: '#app', router: Router, template: '<App/>' });
methods: { login(){ ... this.$bus.$emit('my-event', 'hello'); } }
created: { this.$bus.$on('my-event', (eventData) => { console.log(eventData); }) }
|
这样当在 componentA 中执行 login 时,componentB 中就会打印 hello,似乎很对。
问题
假设有 componentC ,当你 B 和 C 之间反复切换几次路由后,再去 A 执行 login 会发现, B 中一下子打印了多次 hello ,而且路由切换几次,就会多打印几次。
解决
这个问题产生的根源在于没有在组件切换时正确的释放事件订阅。 B 正确写法应该为:
1 2 3 4 5 6 7 8 9 10 11 12 13
| created: { this.$bus.$on('my-event', this.handleMyEvent) }, methods: { handleMyEvent(eventData) { console.log(eventData) } },
beforeDestroy() { this.$bus.$off('my-event', this.handleMyEvent) }
|