In our pursuit of being able to handle large, scalable, maintainable web apps we became familiar with and learned about Vue Components. We learned how to:
- Define a component.
- Instantiate a component.
- Pass data to a component using props.
In this tutorial, we’ll learn how to trigger events in the app based on some user action registered by our “child” component.
As we build out the blog feature, it may become necessary for our “child” components to communicate back to the “parent” app. For example, we may decide to include a feature to vote on comments. Let’s implement this now, and we’ll start by adding a button to the user-comment component from the previous tutorial
The above component employs a template literal to allow our template to be more readable and span across multiple lines, rather than being written in a single line.
Our most immediate problem right now is the fact that nothing happens when the thumbs up icon is pressed. Let’s fix this.
The parent app has the ability to listen to a particular event on a component:
When the component triggers a thumbs-up event, we will then call the
thumbsUp method, which we must implement in the app:
With the parent listening for a child’s
thumbsUp event, we must now trigger this event on icon click. To achieve this we will emit an event using the
You may also like: How and Why We Moved to Vue.js.
Listening for thumbsUp event
As you can see, the
thumbsUp method gets triggered when the icons is pressed. We have successfully emitted an event from the child component to the parent. How about passing some data from the child to the parent? Let’s pass the comments id so the parent can know which comments should receive the new like.
You can adjust the parents
thumbsUp method to show us what’s being passed from the child
Don’t forget to pass this event, as per below code block
As you can see in the screenshot below, we now receive the id of the comment that was liked!
Notification that comment was liked
To update a comment’s number of likes, we must naturally first add that property to our comments starting with a default value of 0
Now, we can search the comments array by id and increment the number of likes
To ensure that our “Like” mechanism works, let’s display the number of likes next to the icon inside the child component
If you followed the tutorial correctly, you now have a working comment-like mechanism that looks like the following
In this tutorial, you’ve learned how to handle component events and how to literally “emit” them to the parent. This is a feature that I think you’ll use quite often. As a challenge, I would suggest that you also implement a dislike button that decrements the number of likes for each comment following the methods you’ve learned today.
The code for this tutorial is available here.