VueJS Child Components – Event Emitters

Alex Scott
Aug 26, 2017 · 1 min read

One thing I get asked quite often, is how to pass data or events from a child component to the parent components. Another example is, courtesy of @micahgodbolt, what’s the best way to have a button component do something?

This is quite a simple problem but can be quite daunting for newbies or for those coming from other frameworks. The answer to the solution lies with Vue’s built in event emitters.


The Button

First we will setup the most basic child component that consists of a button and a click handler that emits our button click event to the parent.


The Parent

Now we will setup our parent component which basically just renders our child component and handles the emitted event.


The Results

Given the two components above, when these are rendered in a VueJS app, the button emits and event with a data payload of ‘Button Clicked!’.

When this event is emitted, the parent receives the event and displays the data payload in an alert followed by in the console.

What we have is event emitters in their most simplest form but they can be expanded upon to do so much more.

Having said this though, sometimes event emitters aren’t the right way to go and it may be best to actually handle the event from within the child components, identifying what data to manipulate using props.

)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade