In the previous part of the tutorial we finished app, where data is passed from the parent into the child with Props.
Now, it is time to send some data back, from child component to the parent. In the HTML templates of the child components, there are two buttons added:
- return student to school without class assignment
- say goodbye to student and remove him from the class as well as from the school
In Vue.js words I need to emit event from child component, that means it becomes available outside the instance. And, what is important, data can be passed to the event, too.
Next step, when event, optionally with data, is emitted, parent component has to be able to listen to this change. Once seen is better than a hundred times to hear:
Vue.js: Child to Parent Component Communication
Emit Event and Listen to Event
You can see new methods added in both child components. They represent two functions mentioned above – return student back to school (returnBack) and remove student completely (removeStudent).
Firstly, they do the same job, remove student from the current class. Then, they emit event (“return” or “decrease”) with data to be accessible.
In the parent component, in HTML template, there is a listener v-on for each event:
v-on:decrease="leaveSchool" v-on:return="returnedStudentOne" v-on:decrease="leaveSchool" v-on:return="returnedStudentTwo"
It means, vue – on “decrease” (or “return”) event emitting in child component, trigger “leaveSchool” (or “returnedStudentOne” or “returnedStudentTwo”) methods in the parent component.
There is no need to explicitely tell, that we expect some data from the child event, Vue.js does this for us automatically.
Emitted event with data is listened by parent component and can be processed. In my case, statistics are changed, and if student is returned to school, student name is pushed into the proper list.
We are almost done, but as people make mistakes, it would nice to have a possibility to switch student from one class directly to another.
Thinking about Vue.js, this is child -> child component communication, what will be covered in the next part of the tutorial.