Vue $emit() Method.

Emit a Custom Event

There is a need to send information from the component to the parent, and we use the built-in method $emit() to do that.

We already have the toggleFavorite method inside the FoodItem.vue component that runs when the toggle button is clicked. Now let’s remove the existing line and add a line to emit our custom event ‘toggle-favorite’:

FoodItem.vue:

methods: {
  toggleFavorite() {
    this.foodIsFavorite = !this.foodIsFavorite;
    this.$emit('toggle-Favorite');
  }
}
 

We can choose the name of our custom event, but it is normal to use kebab-case for emit events.

Receive an Emit Event

The custom emit event ‘toggle-favorite’ is now emitted from the FoodItem.vue component, but we need to listen to the event in the App.vue parent and call a method that does something so that we can see that the event happened.

We listen to the event with the shorthand @ instead of v-on: in App.vue where the component is created:

Example

Get your own Vue Server

Listen to the ‘toggle-favorite’ event in App.vue:

<food-item
  v-for="x in foods"
  :key="x.name"
  :food-name="x.name"
  :food-desc="x.desc"
  :is-favorite="x.favorite"
  @toggle-favorite="receiveEmit"
/>
 

When our custom ‘toggle-favorite’ event happens, we need to create the receiveEmit method in App.vue so that we can see that the event happened:

methods: {
  receiveEmit() {
    alert('Hello World!');
  }
}

Leave a comment

Your email address will not be published. Required fields are marked *