How to communicate between components in Lesson 11 


1. The parent component passes the value to the child component

 

1.1  Other components pass values ​​when using the login component; pass the title value to the <test> component in the index : 

 

picture

1.2  Accept the values ​​passed from the outside world to the inside of the component through props , receive data in the < test > component, and display it:

 

picture

 

picture


//document.getElementById, can only be used in H5 , in the WeChat applet, an error will be reported

 

picture


picture

Comment out, no more errors:

 

picture

2. The child component passes the value to the parent component

2.1 Passing parameters by triggering events through $emit

 

picture

 

picture

 

// At this point, the custom event myEven is triggered by $emit ; the second parameter passes the value to the parent component :

 

picture

2.2 The parent component defines custom events and receives parameters

 

picture

 

picture

You can save the passed value:

 

picture

 

picture

 

3. Brother component communication

 

picture

 

picture

 

picture

 

picture

 

picture

 

picture

( 1 ) Import a and b components:

 

picture

(2) Register components:

 

picture

(3) Using components

 

picture

 

picture

 

picture

 

picture

 

( 1 ) uni.$emit(eventName,OBJECT)

Trigger a global custom event, and additional parameters will be passed to the listener callback function.

 

( 2 ) uni.$on(eventName,callback)

Listen to the global custom event, the event is triggered by uni.$emit , and the callback function will receive the incoming parameters of the event triggering function.

 

 

In the b component, // use $on to register an updateNum event, and the second parameter is the event function body (callback function):

 

picture

In the a component, // through $emit , the updateNum event registered in the b component is triggered , and the second parameter is to pass the value:

 

picture

 

picture