vue-全局事件总线(任意组件间通讯)-beforeCreate

86 阅读1分钟

image.png

image.png

安装全局事件总线的时候用到了生命周期函数 beforeCreate

beforeCreate 此时还无法访问到data中的数据,和methods中的方法

全局事件总线,详细代码过程如下:

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

实现兄弟组件之间的通讯:

//school组件
<template>
  <div>
    <h2>{{ name }}</h2>
    <h2>{{ address }}</h2>
  </div>
</template>

<script>
export default {
  name: "School",
  data() {
    return {
      name: "培正",
      address: "广州",
    };
  },
  mounted() {
      //接收数据,school想要接收数据,则在school组件给$bus绑定自定义事件
      //$on 用来注册自定义事件的
    this.$bus.$on("hello", (name) => {
      console.log("我是school组件,我收到了", name);
    });
  },
  
  //解绑组件所用到的事件
  beforeDestroy() {
    this.$bus.$off("hello");
  },
};
</script>

//students组价
<template>
  <div>
    <h2>{{ name }}</h2>
    <h2>{{ age }}</h2>
    <button @click="sendStudentsName">把学生名给shcool组件</button>
  </div>
</template>

<script>
export default {
  name: "Students",
  data() {
    return {
      name: "wanjiapeng",
      age: 18,
    };
  },
  methods: {
     // $emit手动触发当前实例上的一个指定事件
    sendStudentsName() {
      this.$bus.$emit("hello", this.name); //将数据传递给school组件
    },
  },
};
</script>