Parent-Child Communication in Vue. From Child to Parent

Liuba Kuibida
2 min readMar 8, 2022

Hello, my dear followers and Vue lovers. I’m writing this post from my parent’s place. Thirteen days ago, Russia invaded Ukraine, and I had to leave my home in Kharkiv. Now I’m safe, but some of my friends, colleagues, and relatives are still in the city, which is being bombed days and nights, and I am afraid for their lives. One of the most beautiful cities in Ukraine methodically and purposefully is being turned into a ruin. I can’t find the words to describe my anger and sorrow when I see Ukrainian peaceful citizens suffering from the war. In case you want to help, please, support Ukrainian Armed Forces. We fight for freedom and democracy in Ukraine and the world.

I chose the Star Wars theme just before the war started, kind of prophetic, don’t you think? Relation between Luke and his father is dramatic and recognizable, and I wanted to use it in my small project about components’ communication in Vue. There are two components — Parent.vue and Child.vue. The child has a text field for a message, which should be sent to its parent and displayed in it. How to achieve this?

We need to use $emit, which allows us to send custom events from a child component to its parent. Each Vue $emit call can pass two arguments: the event name and a payload object (optional). Let’s check how it works on the real-world example. In my codesandbox (visit this link to play around with code), the parent component listens for a custom event and confers the received value to its data:

Now we need our child component to listen for the native input event and then emit its event. To pass the value of our original change event, we need to send our custom event with the event payload — in this case, the event.target.value — as a second parameter. It looks like this:

That’s all the magic. The message from the child component is displayed in its parent. Note, that this is an example of emitting inline events in Vue. If you are curious about other ways of using $emit in your code, watch this video. Thanks for reading. Stay tuned.

--

--

Liuba Kuibida

Master of cultural studies. Self-taught programmer. Stand with Ukraine 🇺🇦