Global Event Bus (GlobalEventBus)
- A way of communication between components, suitable for any communication between components.
Install the global event bus:
new Vue({ ...... beforeCreate() { Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm }, ...... })
Using the event bus:
1. Receive data: If component A wants to receive data, it binds a custom event to $bus in component A, and the callback of the event stays in component A itself.
methods(){ demo(data){......} } ...... mounted() { this.$bus.$on('xxxx',this.demo) }
2. Provide data: this.$bus.$emit('xxxx',data)
It is best to use $off in the beforeDestroy hook to unbind the events used by the current component.
Message Subscription and Publishing (pubsub)
- A way of communication between components, suitable for any communication between components.
- Steps for usage:
1. Install pubsub: npm i pubsub-js
2. Import: import pubsub from 'pubsub-js'
3. Receive data: If component A wants to receive data, it subscribes to the message in component A, and the subscribed callback stays in component A itself.
methods(){ demo(data){......} } ...... mounted() { this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息 }
4. Provide data: pubsub.publish('xxx', data)
5. It is best to use ```PubSub.unsubscribe(pid)``` to unsubscribe in the beforeDestroy hook.