美文网首页
全局事件总线(GlobalEventBus)

全局事件总线(GlobalEventBus)

作者: 5cc9c8608284 | 来源:发表于2022-03-19 10:47 被阅读0次
    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')
    

    相关文章

      网友评论

          本文标题:全局事件总线(GlobalEventBus)

          本文链接:https://www.haomeiwen.com/subject/hxuodrtx.html