1、主要功能
用于组件之间的数据传递,多数用于兄弟组件传递信息,任意组件都可以通信
父=》子组件用props传递,子=》父组件用自定义事件
2、全局事件总线的实现
一、在入口文件增加全局事件总线
在main.js中
new Vue({
el:'#app',
render: h => h(App),
beforeCreate(){
// 安装全局事件总线
Vue.prototype.$bus=this
}
})
二、使用全局事件总线
例如在两个组件中实现通信,有student.vue,school.vue两个组件
实现student.vue把学生姓名发送给school.vue
在student.vue中有
<button @click="sendstudentname">将学生姓名发送给school</button>
methods:{
sendstudentname(){
this.$bus.$emit('sendname',this.name)
}
}
其中sendname代表发送出去的数据名字
在school.vue组件中
进行接收数据
mounted(){
this.$bus.$on('sendname',(data)=>{
console.log(data)
})
}
data表示收到的数据
注意
当组件销毁时要去掉当前组件的全局事件总线
beforeDestroy(){
this.$bus.$off('sendname')
}
一定要在this.$bus.$off()里面传递销毁的事件总线的名字,不然会全部销毁事件总线