Vue-Global Event Bus (GlobalEventBus)

Global Event Bus (GlobalEventBus)

The global event bus is a particularly powerful communication method in components in Vue. It can realize communication in any component, and two components can communicate with each other. Just like a walkie-talkie, it is also used in development. Special many

1 Write a case

First, prepare two components, which are brothers and managed by App

A simple page is as follows

2 Install the global event bus

Define $bus (bus) in main.js, because main.js is the entry point of the entire program, and then use the hook function beforeCreate in vm to create it before vm is created, so that the global vc and vm can see it

 beforeCreate(){
         // 安装全局事件总线
        Vue.prototype.$bus=this
    }

3 Components pass data using midline

After the global event is installed, it can be used. The following demonstrates passing data in sibling components

4 Unbind the event before the component is destroyed

Because everyone is using the bus, if one day the component is destroyed, then this component still occupies the bus and will occupy resources, so it is best to unbind the event before the component is destroyed

5 summary

  1. A way of communication between components, suitable for any communication between components
  2. Install the global event bus:
new Vue({
        ......
        beforeCreate() {
                Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
        },
    ......
}) 
  1. Using the event bus:

    1. Receive data: If component A wants to receive data, then bind a custom event to $bus in component A, and the callback of the event stays in component A itself.
    2. methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.$bus.$on('xxxx',this.demo)
      }
      
    3. Provide data: his. bus . bus.b u s . emit('xxxx', data)
  2. It is best to use $off in the beforeDestroy hook to unbind the events used by the current component.

Guess you like

Origin blog.csdn.net/weixin_46713508/article/details/131344415