Vue2基础篇-29-全局事件总线(GlobalEventBus)

1. 简介

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

  2. 安装全局事件总线:

    new Vue({
    	......
    	beforeCreate() {
    		Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
    	},
        ......
    }) 
    
  3. 使用事件总线:

    1. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.$bus.$on('xxxx',this.demo)
      }
      
    2. 提供数据:this.$bus.$emit('xxxx',数据)

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

2. demo

2.1 安装全局事件总线

// 引入Vue
import Vue from "vue";
// 引入App
import App from "./App.vue";

// 关闭Vue的生产提示
Vue.config.productionTip = false;

// 创建Vm
new Vue({
  el: "#app",
  render: (h) => h(App),
  beforeCreate() {
    //安装全局事件总线
    Vue.prototype.$bus = this;
  },
});

2.2 学生组件 绑定事件

<template>
  <div>
    <h2>学生名称为{{ StudentName }}</h2>
    <h2>学生地址为{{ StudentAddress }}</h2>
  </div>
</template>
<script>
export default {
  name: "Student",
  data() {
    return {
      StudentName: "张三",
      StudentAddress: "金桥",
    };
  },
  mounted() {
    this.$bus.$on("sendSchoolName", (data) => {
      console.log("我是Student组件,收到了数据", data);
    });
  },
};
</script>
<style></style>

2.3 学校组件 发送数据

<template>
  <div>
    <h2>学校名称为{{ SchoolName }}</h2>
    <h2>学校地址为{{ SchoolAddress }}</h2>
    <button @click="sendSchoolName">将学校名称传递给学生</button>
  </div>
</template>
<script>
export default {
  name: "School",
  data() {
    return {
      SchoolName: "大学",
      SchoolAddress: "张江",
    };
  },
  methods: {
    sendSchoolName() {
      this.$bus.$emit("sendSchoolName", this.SchoolName);
    },
  },
};
</script>
<style></style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alan0517

感谢您的鼓励与支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值