Vue Emit Event

Posted on  by admin

Vue $emit lets us emit, or send, custom events from a child component to its parent. In a standard Vue flow, this is the best way to trigger certain events (like closing a popup, for example) or to send data from a child component (like making a custom input).

This article focuses in detail on Vue $emit, click here for a broader guide on handling Vue events. Each Vue $emit call can pass two arguments:. The event name – this is the name that we can listen to in our parent component.

A payload object – data that we want to pass with the event; this is optional. Here’s an example of a typical emit using both parameters $emit('event-name', data).

There are a bunch of different ways to use Vue $emit in your code, the three that I’ll be covering in this article are….

Step 4 — Removing Event Listeners

Inline using $emit. Options API – this.$emit. Composition API – context.emit. Each of them has its own pros/cons depending on your case, so let’s just check out an example in each and you can see which works for you. An example of where you might want to send data out of a component is when building your own custom form input – let’s imagine a custom text input.

Since, we’re wrapping our text input, when we implement MyInput.vue, we won’t be able to listen to the standard input events like @change. Let’s say that our parent component is set up like this, listening for a custom custom-change event and logging its value.

Emitting Inline Events in Vue

To achieve this, we need our custom text input to listen for the native input events, and then emit its own event. To actually 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.

Now if we type in our custom input, our parent component will be properly logging all of our changes. Now, let’s move on to emitting events from our script section. Like almost everything in Vue 3, we have the choice of using the Options API or the Composition API to emit custom events from our component.

In the Options API, the $emit method can be called using this. So in our same MyInput example, let’s say that instead of calling $emit in our template, we call a Vue method first instead. Then, inside our method, we can call this.$emit and same as last time, pass it our event.target.value.

Conclusion