Fixing the add to cart event

Now that we've added another component, our add-to-cart event will no longer emit back to the app component as the Home component is now rendering the products. To fix this, we'll need to emit the event twice so it gets back to the main app component.

If you're thinking that emitting an event twice could get tricky to manage, you're spot on. Later, when we integrate Vuex, we won't need to emit any events at all, however, emitting events and passing props in this way is a common framework pattern and one that you would use for smaller apps, so it's great to know.

Here's what our new set-up will look like:

Module 1 - Emitting events

Learning Objectives

Fixing the Add to cart event

Step 1

We're already emitting the event from the Product component, so our first port of call is to add some code in the Home component to handle the emit from the Product component. In your Home component, add the following method to the methods object:

updateCart(productId) {
  this.$emit('update-cart', productId);
}

Step 2

Then in your index.html, your router view needs to be modified to register the update-cart event with the Home component:

<router-view v-bind:products="this.products" v-on:update-cart="updateCart" />

And that's it! You should find that the event emits up two levels while passing along the Product ID. This then gets pushed to the cart array in the main app component.

Assignment

No coding challenge this time. Instead, review the code we've written and ensure you understand how the events flow between components. Follow the emitting of the event from the child component up to the app component here to help your understanding.