Father and son components

What are parent-child components?

It is generally considered that the component whose ID is “root “is the parent and all other components are children.

For example, I want to create a child component named “counter”

We need to create a new script:



At the same time, the parent component is also associated with the child component:



Also inside the parent component, embed the child component:

The parent component passes data to the child component in the form of properties

Passed by the :count= “0” attribute



For example, if you want to implement, click on the child component, the number +1

The parent component passes data to the child component

We need to add a click method to the child component:



But at this point, the question arises:

You don’t modify the parent component passed data directly, this is because, there is a single data stream in the vue, the concept of the parent component can be passed to the child components parameters, transfer of parameters can be modified, but the child components to get their data cannot modify the parent component, such as the parent component to the child components passed 1 3, child components can be used, but you cannot be modified This is because if you modify data of a reference type, the referenced data may also be referenced by other child components, which will modify other content.



Modification mode:

Define a data in the child component summary, and define a function in the data so that, instead of modifying the parent component’s properties, the modification is done through a mediation.

The child component passes data to the parent

Child components pass data to parent components in the form of events

The parent component defines a div with a total variable that calculates the sum of two numbers.



Add the triggering event to the child component



The parent component adds a listening event, which is also inc.



Then, in the root instance, add the triggered method:



In this way, the child component passes the value to the parent component, and the parent component can act on the value.