Communication with the Parent Component

Learn about emits and slots used for communication with parent components in Vue.

We'll cover the following

Overview

So far, we’ve seen how to get data into a component using props, but how do we allow our component to communicate information back? In React, it’s common to pass a callback functionA callback function is a function that is passed as an argument to another function and is executed after the completion of that function's task. to a component to allow for data to be sent back. Although it’s also possible to do this in Vue, the preferred way is to use events.

We can listen to the DOM events (such as mouse clicks) on HTML elements in the template and connect them up to handler methods. It’s actually very straightforward to have components emit their own custom events and listen for them in exactly the same way.

The $emit() method

In order to emit custom events, Vue components have access to an emit() method. We can call this from the template (as in the example below) or from the component’s methods (as this.emit()). It takes an event name as its first argument, which is what the parent component will listen for. We can also provide additional arguments if we wish that will be passed as parameters to any listening callback function.

Here’s a SearchBox.vue component:

Get hands-on with 1200+ tech skills courses.