Communicating Events
We have seen how to communicate data between components, but how do we communicate events between components?
Let's take our example, we have a button that adds a product to the cart. We want to be able to click that button and have the cart update. We can do this by emitting an event from the child component and listening for it in the parent component.
First, we need to change our method to emit an event instead of directly updating the cart.
From this:
To this:
in here we are creating a custom event called add-to-cart
and emitting it from the child component. and using the id of the product as a parameter.
Now let's add a listener for that event in the parent component.
on the line
we are going to add
for make this updateCart function work, we need to create it in the main.js file.
That's it! Now when we click the button, the cart will update.