vue-事件总线$bus的使用

作用

实现不同组件之间进行通信(非父子关系)。

 

原理

$bus就是vue原型上添加的一个vue实例,用于存储、监听以及触发事件。

 

实现步骤

  1. 在main.js文件中注册事件总线
Vue.prototype.$bus = new Vue();
  1. 在需要发送信息的组件中发送事件
this.$bus.$emit("eventname") //无参传递,eventname表示事件名
this.$bus.$emit("eventname",params) //带参传递,params表示传递的参数
  1. 在需要接收信息的组件中接收事件
//有参
this.$bus.$on("eventname",(params)=>{

});

//无参
this.$bus.$on('eventname', () => {
});
  1. 在接收信息的组件beforeDestroy事件中销毁接收事件
beforeDestroy() {
    this.$bus.$off('eventname');
}
posted @ 2024-05-08 10:46  相遇就是有缘  阅读(975)  评论(0)    收藏  举报