Vue CLI 全局事件总线

原理

它的原理是给 Vue 的原型对象上面添加一个属性。这样的话我所有组件的都可以访问到这个属性,然后可以通过这个属性来访问其他组件给这个属性上面绑定的一些方法,从而去传递数据。而且这个属性还可以去访问 Vue 实例对象上的方法。因为 Vue 组件构造函数的原型对象的原型对象是指向 Vue 的原型对象的
全局事件总线(GlobalEventBus)
一种可以在任意组件间通信的方式,本质上就是一个对象,它必须满足以下条件

  1. 所有的组件对象都必须能看见他
  2. 这个对象必须能够使用 $on $emit $off 方法去绑定、触发和解绑事件
    3.使用事件总线:
    ①.接收数据:A组件想接收数据,则在A组件中给 $bus 绑定自定义事件,事件的回调留在A组件自身
methods(){
	demo(data){......}
}
......
mounted() {
    //给$bus绑定hello事件
    this.$bus.$on("xxx",this.demo)
    //或者
     //this.$bus.$on("xxx",(data)=>{
     console.log("执行事件")
})
}

或者不写上边的 method,直接写成一个箭头函数

②.B组件 提供数据:this. b u s . bus. bus.emit( " xxx",数据)

4.最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件

使用

1,定义全局事件总线
在main.js中定义

new Vue({
    render: h => h(App),
    beforeCreate() {
        Vue.prototype.$bus = this//安装全局事件总线,$bus就相当于当前vm
    }
}).$mount('#app')

2,使用事件总线
School.vue 中给 $bus 绑定 demo事件

<template>
  <!--组件的结构-->
  <div class="school">
    <h2>学校名称:{{ name }}</h2>
    <h2>学校地址:{{ address }}</h2>
    <span>传过来的消息:{{ msg }}</span>
  </div>
</template>

<script>
import pubsub from "pubsub-js";

//组件交互相关的代码(数据、方法等)
export default {
  name: "SchoolD",
  data() {
    return {
      name: "北京大学",
      address: "北京",
      msg: "",
    };
  },
  mounted() {
    this.$bus.$on("demo", (data) => {
      console.log("我是school组件,到了数据:" + data);
    });

    this.pubid = pubsub.subscribe("hello", (msgName, data) => {
      this.msg = data;
      console.log(
        "有人发布了hello消息," + msgName + "回调执行了,收到数据:" + data
      );
    });
  },
  beforeDestroy() {
    pubsub.unsubscribe(this.pubid);
    this.$bus.$off("demo");//最好在销毁前 解绑事件
  },
  methods: {
    // hello(msgName, data) {
    //   //两个参数 第一个是方法名 第二个是传过来的数据
    //   this.msg = data;
    //   console.log(
    //     "有人发布了hello消息," + msgName + "回调执行了,收到数据:" + data
    //   );
    // },
  },
};
</script>

3,在student 组件中触发事件

<template>
  <!--组件的结构-->
  <div class="student">
    <h2>学生姓名:{{ name }}</h2>
    <h2>学生年龄:{{ age }}</h2>
    <button ="send">School组件发送学生姓名</button>
  </div>
</template>

<script>
// import pubsub from "pubsub-js";
//组件交互相关的代码(数据、方法等)
export default {
  name: "StudentD",
  data() {
    return {
      name: "张三",
      age: 18,
    };
  },
  methods: {
    // sendStudentName() {
    //   pubsub.publish("demo", 666);
    // },
    send() {
      this.$bus.$emit("demo", "张三");
    },
  },
};
</script>

4,结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值