Implementation Method for communication between vue2.0 parent and child components, and vue2.0 parent and child components
1. The parent component transmits data to the child component.
How do I transmit the data of the parent component to the child component? The props attribute can be used for implementation.
Parent component:
<Parent> <child: child-msg = "msg"> </child> // here, you must use "-" instead of "camper". </parent> data () {return {msg: [1, 2, 3]};}
Child components receive data through props:
Method 1:
props: ['childMsg']
Method 2:
Props: {childMsg: Array // you can specify the input type. If the type is incorrect, a warning is displayed.} props: {childMsg: {type: Array, default, 0] // you can specify the default value }}
In this way, the parent component transmits data to the child component.
2. Communication between child components and parent Components
What if the child component wants to change the data? This is not allowed in vue because vue only allows one-way data transmission. In this case, we can trigger a Custom Event to notify the parent component to change data, to change the sub-component data.
Use v-on to bind custom events
Each Vue instance implements the Events interface, namely:
- Use $ on (eventName) to listen for events
- Use $ emit (eventName) to trigger an event
The parent component can directly use v-on to monitor the events triggered by the Child component.
Child components:
<Template> <div @ click = "up"> </div> </template> methods: {up () {this. $ emit ('resultedchang', 'hehe '); // actively triggers the resultChange method, and 'He' is the data passed to the parent component }}
Parent component:
<Div> <child @ on-result-change = "mychangHandle": msg = "msg"> </child> // listen to the upup event triggered by the child component, then call the change method </div> methods: {mychangHandle (msg) {this. msg = msg ;}}
The trigger event uses the Custom Event name in the camper format. In the parent component, you can use the on-evnet-name format to listen for the event.
3. Communication between any components
If the two components are not parent and child components, how can we communicate? In this case, you can use eventHub to implement communication.
The so-called eventHub is to create an event center, which is equivalent to a transfer station. It can be used to deliver events and receive events.
Use an empty Vue instance as the central event bus:
Let Hub = new Vue (); // create an event center. Make sure that the Hub is placed globally.
Trigger of Component 1:
<Div @ click = "eve"> </div> methods: {eve () {Hub. $ emit ('change', 'hei'); // Hub trigger event }}
Receive from component 2:
<Div> </div> created () {Hub. $ on ('change', () =>{// Hub receives the event this. msg = 'hehes ';});}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.