Listen for Custom Emitted Events in Vue 3 Parent Components

Share this video with your friends

Social Share Links

Send Tweet

Sometimes we need a child component to change the state of its parent component.

We can do that by emitting an event using the globally defined function, defineEmits, and listening for it where the component is used.

Instructor: [0:00] Inside my modal, I want an updateCraft form. I want to pass in the crafts that we have.

[0:08] I want to bind a prop called craft with the craft that we have, so that we can initialize that form with the current data. I'll need to import this form here -- let's do that up here -- and I'll need to create it. Just make sure that it's working. Excellent.

[0:34] In my script setup tag, the first thing I want to do is define my props. I'm going to be expecting that craft to arrive as an object, so let's make sure that's what we've got. Cool. We're going to want the form with some fields, and we're going to want a few buttons. We're going to want that Cancel button, and we're going to want an Update button.

[1:02] When I click my Cancel button, I want to emit an event. To do that, I'm going to create a variable called emit, and I'm going to assign that to defineEmits, which is a globally defined function in Vue, which takes an array of emit events that we want to consider. I want it to have a close event. When I click my Cancel button, I want to emit a close, like that.

[1:29] I go back to my application and refresh. If I press the Update button, I get my form with my View Tools, so they are open and ready. When I click this Cancel button, you see I get my mousedown and mouseup, but I also get this close that's being emitted by the form.

[1:45] Back in my CraftView, when this component gets a close, so that's equivalent to the emit event that we defined before, we want to change the modal state. I want to close, we want to change the modal state like that. Now, when I refresh this form, I hit Update here, console here. That emit event is being picked up by the parent, and the parent then is toggling the showModal event.