@TOC

For example, Vue’s global event $BUS component communicates using messages similar to subscription and publishing

The following are personal opinions

First global register $bus mounted on Vue’s Prototype

The import of the bus event mounts the \bus to the Vue object prototype at ==main.js== import

The first method: main.js

// $bus Import event bus
Vue.prototype.$bus = new Vue()
Copy the code

The second method: write inside the vue construct

new Vue({
  name: 'App'.rander: h= > h(App),
  beforeCreate () {
 	Vue.prototype.$bus = this}})Copy the code

$bus.$emit(‘name’, data)

Register an event like div == and send event ==


<div @click="handle"></div>
// in the vue method
export default {
  name: 'LeaderBoard'.methods: {
		handle () {
		this.$bus.$emit('Name of event', Data) // The name of the event for the first argument and the Data to be carried in the second argument can not be written}}}Copy the code

$bus.$on(‘name’, data)

Write == receive event == in the component lifecycle function


export default {
  name: 'LeaderBoard'.mounted: {
   this.$bus.$on('Name of event', Data / () = > { // The first parameter is the name of the event. The second parameter is Data. The Data to be received cannot be written
		// Something that needs to be operated
	})
  }
}
</script>
Copy the code

Fourth, you can choose to disable the event bus $bus when the component is destroyed, and do not occupy the event


export default {
  name: 'LeaderBoard'.mounted: {
   this.$bus.$on('Name of event', Data / () = > { // The first parameter is the name of the event. The second parameter is Data. The Data to be received cannot be written
		// Something that needs to be operated
	})
  },
  beforeDestroy () {
  	this.$bus.$off('Name of event') // Cancel one
  	this.$bus.$off() // Cancel all
  }
}
</script>
Copy the code

pubsuh

  1. A communication mode between components. It can be used for communication between any components.
  2. Procedure 1. Install pubSub: NPM I pubsub-js 2. Import pubsub from ‘pubsub-js’ 3. Receive data: Component A wants to receive data, it subscribes to the message in component A, and the callback for the subscription is left in component A itself.
methods(){
demo(data){... }}...mounted() {
	this.pid = pubsub.subscribe( 'xxx ' ,this.demo) // Subscribe to the message
}
Copy the code
  1. Provide data:Publish (' XXX ', data)
  2. In the bestbeforeDestroyIn the hook, usePubSub.unsubscribe(pid)Go to theUnsubscribe.