首页 > 其他分享 >day81- 全局事件总线

day81- 全局事件总线

时间:2023-03-02 11:35:01浏览次数:41  
标签:bus 总线 day81 事件 组件 全局 ....

全局事件总线

在组件间通信的一种方式,适用于任意组件通信

之前实现的是父子组件的通信,如果兄弟组件想要相互传递消息就需要先向app组件传信息,app设置回调再往兄弟组件中传递信息

全局事件总线首先在main.js中安装全局事件总线,再在接受数据方绑定自定义事件

在传递数据一方提供数据

类似:student向school提供数据

先在student中配置自定义事件函数

 
export default {
   data() {
     return {
       name: '张三',
       sex: 'boy'
     }
   },
   methods:{
     sendStudentName() {
       this.$bus.$emit('hello',this.name)
     }
   }
 }

 

在school中接收数据

 mounted() {
   // console.log('school',this)
   this.$bus.$on('hello',(data)=>{
     console.log('school get ',data)
   })
 },
 beforeDestroy() {
   this.$bus.$off('hello')
 }

 

完成兄弟之间的消息传递

总结

 /*
  全局事件总线:
   1.一种组件之间通信的方式,适用于任意组件通信
   2.安装全局事件总线:
     new Vue({
       ....
       beforeCreate(){
         Vue.prototype.$bus = this //安装全局事件总线
       }
       ....
     })
   3.使用事件总线:
     1.接受数据:a组件想要接受数据,则在a组件中给$bus绑定自定义事件,事件的回调在a自身
     methods(){
       demo(data){....}
     }
     ....
     mounted(){
       this.$bus.$on('xxx',this.demo)
     }
     2.提供数据:this.$bus.$emit('xxxx',数据)
   4.最好在beforeDestrory钩子中,用$off去解绑当前组件用到的事件
 */

 

over

标签:bus,总线,day81,事件,组件,全局,....
From: https://www.cnblogs.com/GUGUZIZI/p/17171187.html

相关文章