全局事件总线
 

 
- 功能:可以解决所有组件之间通信传数据的问题
 - 原理:通过一个共享对象,将所有组件全部绑定到对象上,即可通过这个对象实现组件与组件之间的传递数据,而这个共享对象叫做全局事件总线。
 
 
如何分清楚谁是发送方,谁是接收方?谁用绑定事件,谁用触发事件?
 
- 假设:我向你传送数据,我是发送方,你是接收方。 
- 若我不向你发送数据,则你就不知道数据的内容,无法拿取(绑定)。(我不触发,你不能绑定,因为你没有数据)
 - 只有我发送数据给你,你才能知道数据的内容,才能对数据进行拿取。(谁发送谁触发,谁拿取谁绑定)
 
  
 
共享对象创建位置:main.js文件
 
 
const VueComponentConstructor = Vue.extend({})
const vc = new VueComponentConstructor()
Vue.prototype.$bus = vc
 
- 第二种方法(常用):使用原有的vm对象 
- 在Vue初始化时(beforeCreate),创建共享对象vm
 
  
 
new Vue({el : '#app',render: h => h(App),beforeCreate(){Vue.prototype.$bus = this}
})
 
以上代码中出现的$bus有什么作用?
 
- $bus:事件总线,用来管理总线。
 - 其他组件在调用vc共享对象时可通过
this.$bus.$on() 和 this.$bus.$emit()来绑定或触发事件 
 
数据发送方:触发事件$emit
 
<template><div><button @click="triggerEvent">触发事件</button></div>
</template><script>export default {name : 'Vip',data(){return{name : 'zhangsan'}},methods : {triggerEvent(){this.$bus.$emit('event', this.name)}}}
</script>
 
数据接收方:绑定事件$on
 
<template><div><Vip></Vip></div>
</template><script>import Vip from './components/Vip.vue'export default {name : 'App',mounted() {this.$bus.$on('event', this.test)},methods : {test(name){console.log(name);}},components : {Vip}}
</script>console.log(name);}},components : {Vip}}
</script>