美文网首页
全局事件总线(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')

相关文章

  • 22.Vue全局事件总线(GlobalEventBus)

    一种组件间通信的方式,适用于任意组件间通信 安装全局事件总线:new Vue({ ...... beforeCre...

  • 全局事件总线

    全局事件总线 1、一种组件间相互通信的方式,适用于任意组件间通信。 2、安装全局事件总线: new ...

  • 全局事件总线

    1.一种组件间通信方式,适用于任意组件间通信2.安装全局事件总线new Vue({...beforeCreate ...

  • $bus 全局事件总线

    组件之间除了父子这种有关系的,有联系的,可以通过父子组件之间通信来实现交流除了这种父子关系的组件,还有没什么联系的...

  • Vue全局事件总线

    添加$bus属性 首先在Vue的prototype原型对象上添加$bus属性,属性的值为当前的Vue对象,作为全局...

  • LiveDataBus

    全局共用的消息事件总线,可代替EventBus解决简单的数据传递功能

  • Vue父子组件间通信(数据传递)

    父---props--->子子---props/自定义事件/全局事件总线/消息订阅与发布--->父任意组件间通信:...

  • antV F2 利用changeSize在windowResiz

    antV f2 windowResize思路:①注册全局总线 提起监听事件;②在app.vue的入口页写下监听事件...

  • 11-全局数据总线

    1. 定义 全局事件总线是一种组件间的通信方式,适用于任意组件之间的通信。事件总线是程序员在工作中的总结,不是新的...

  • vue学习(40)全局事件总线

    思路 首先可以让所有组件访问到尝试1:是不是可以往window身上放一个x?widnow.x=123;虽然其他组件...

网友评论

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

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