Vue message subscription and publishing pubsub
A way of communication between components, suitable for any communication between components.
Steps for usage:
- Install pubsub:
npm i pubsub-js
- Introduce:
import pubsub from 'pubsub-js'
- Receive data: If A component wants to receive data, it subscribes to the message in A component, and the subscribed callback stays in A component itself.
methods:{
demo(data){
}
}
mounted(){
this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
}
- provide data:
pubsub.publish('xxx',数据)
- Finally, in the beforeDestroy hook,
pubsub.unsubscribe(pid)
unsubscribe with