What is the “parent -> child” communication in my case?
School is a parent, which distributes students to the classes = children. At school level I can add new students, and to see statistics, where are students located.
Enough Words, Example Follows
Each component has own “students” array, where all members are stored.
Note: Keep in mind, that while in parent Vue instance data is an object, in components data must be a function.
Then, I dynamically pass chosen student from parent to child (HTML tab) – that’s why colon is before “student” property in the HTML template, e.g.:
If colon is missing, data is triggered as a string “classOneStudent” which would be passed to the child.
But, what is “classOneStudent” property? In the Parent Vue instance, on button click event I pass data to the method, where “classOneStudent” (or “classTwoStudent”) is set and then attached to the “student” property.
The name of the property (in my case “student”) must be the same in the template and in the child component to be able to access data.
How do I catch data in a child component? If I pass only a simple variable like string, number, boolean or even a function, props do the job for me.
Because I can pass as many properties as needed, props can be an array of all parent data. But this is not the only way. Props can be also an object, which might be usable e.g. when validation is needed.
Ok, data arrived into child component, but how to change HTML dynamically to see student automatically added into class list? I use watched property.
Watcher simply monitor the change of the “student” prop in real-time. If it changes, watcher executes the function automatically. In my case, new student is added as a class member into proper class array and his name displays under the class name.
In addition to parent -> child communication, in the Parent Vue instance you may find out some more functions, e.g. to calculate proper count of students in each class, to add new student or remove student from the school list.
Time to Refactor Code
As you can see, in the Parent Vue instance methods, some code is duplicated, what is definitely not the best practice to do.
Let’s merge “addToClassOne” and “addToClassTwo” methods into the one, final code:
That’s it! Data travels from parent to the child components, but, as mentioned in the preview part of the tutorial, this is one-way flow, we need to define child -> parent communication separately.