全局事件总线(GlobalEventBus)

  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 去解绑当前组件所用到的事件。
    5.案例
    利用全局事件总线将Student组件中的name属性传递给School组件

Student.vue组件

<template>
  <div>
    <button @click="sendStudentName">把名字传递给school组件</button>
  </div>
</template>

<script>
export default {
  name: "",

  data() {
    return {
      name: "janny",
    };
  },

  methods: {
    sendStudentName() {
      this.$bus.$emit("hello", this.name);
    },
  },
};
</script>

School.vue组件

<template>
  <div>
    <h1>School组件</h1>
    <h2>{{ name }}</h2>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      name: "小虾皮陈",
      age: 18,
    };
  },
  mounted() {
    this.$bus.$on("hello", (data) => {
      this.name = data;
      console.log("我是School组件,收到了数据", data);
    });
  },
  beforeDestroy() {
    // 在组件销毁的时候解绑事件
    this.$bus.$off("hello");
  },
};
</script>

main.js中的操作:

// 全局事件总线(方案一)
// const Demo = Vue.extend({})
// const d = new Demo()
// Vue.prototype.x = d


new Vue({
  router,
  store,
  render: h => h(App),
  // 全局事件总线(方案二)
  beforeCreate() {
    Vue.prototype.$bus = this //安装全局事件总线
  }
}).$mount('#app')
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容