Introduction: Communication between components, includingChild component ===> parent component communication, parent component === => child component communication, and communication between any componentsThere are three cases, and the specific methods are introduced below:
1. Component custom events
This applies to the communication of the child component ===> parent component
-
Usage scenario: A is the parent component and B is the child component. If B wants to send data to A, it needs to bind custom events to B in A (the event callback is in A).
-
Bind custom events:
-
The first way, in the parent component: < demo@mytest =”test”/> or
-
The second way, in the parent component:
<Demo ref="demo"/ >...mounted(){ this.$refs.xxx.$on('mytest'.this.test) } Copy the code
-
To make a custom event fire only once, you can use the once modifier, or the $once method.
-
-
Emit custom event: this.$emit(‘mytest’, data)
-
Unbind custom event this.$off(‘mytest’)
-
Native DOM events can also be bound to components, requiring the use of native modifiers.
-
Note: when using this.$refs.xxx.$on(‘mytest’, callback) to bind a custom event, either the callback is configured in Methods or the arrow function is used, otherwise the this pointer will fail!
2. GlobalEventBus
Applicable to communication between any components
-
Install the global event bus:
new Vue({ ...... beforeCreate() { Vue.prototype.$bus = this // Install the global event bus. $bus is the vm currently applied},... })Copy the code
-
Using the event bus:
-
Receive data: if component A wants to receive data, it binds A custom event to $bus in component A. The callback of the event remains with component A itself.
methods(){ demo(data){... }}...mounted() { this.$bus.$on('xxxx'.this.demo) } Copy the code
-
This.$bus.$emit(‘ XXXX ‘, data)
-
-
It is best to use $off in the beforeDestroy hook to unbind events used by the current component.
3. Message subscription and publishing
Applicable to any communication between components using steps:
-
Install pubsub: NPM I pubsub-js
-
Import pubsub from ‘pubsub-js’
-
Receive data: If component A wants to receive data, it subscribes to the message in component A, and the subscribed callback remains in component A itself.
methods(){ demo(data){... }}...mounted() { this.pid = pubsub.subscribe('xxx'.this.demo) // Subscribe to the message } Copy the code
-
Publish (‘ XXX ‘, data)
-
It is best to unsubscribe with pubsub. unsubscribe(PID) in the beforeDestroy hook.
4. The slot slot
For parent component === => Child component function: allows parent component to insert HTML structure to child component specified location, is also a way of communication between components divided into default slot, named slot, scope slot
5.vuex
A Vue plug-in for centralized state (data) management in Vue application, centralized management (read/write) of the shared state of multiple components, is also a way of communication between components: when multiple components need to share data