前言:
在vue中实现用公共bus来实现不同组件直接的传值。
实现方法:
1、main.js中在window上挂载一个变量EventBus
window.EventBus = new Vue()
2、传方法页面,必须在页面的销毁阶段传方法,至于原因,请看最下面的原因
beforeDestroy () {
window.EventBus.$emit('getData', 123)
}
3、接受方法页面,必须在created ,至于原因,请看最下面的原因
//注意:这里只能在beforeCreate ,created,和beforeMount这三个钩子函数中监听$on。
created () {
window.EventBus.$on('getData', (msg) => this.getData(msg))
}
destroyed () {
window.EventBus.$off('getData')
}
为什么传要放a页面的befireDestroy里面,获取b要放create,并要加off关闭原因:
参考地址:https://www.cnblogs.com/ljh-dream/articles/10048265.html