We'll see how we can define our own events that our components can emit to their parents. We'll also see how the parent can respond to these events using the v-on
or @
directive, just like any other event.
Instructor: [0:00] So far, we have created these components for bronze, silver, and gold that we can set some tickets and we can add tickets.
[0:11] It changes the internal state of the component, but so far does nothing to the external state. It's not updating the tickets up here, and it's not updating what the route understands about how many tickets are left. To be able to do that, we need to add some custom events to our component.
[0:31] When we click our button to add tickets, we want our component to tell the parent that something has happened. We use the this.emit helper to emit a custom event, and we can name this whatever we like. We can define these in camelCase or in kebab-case. Let's emit the event, buyTickets.
[0:58] If I go to buy two tickets, I'm clicking over here to the timeline. If I buy a ticket, you can see this component event has been emitted.
[1:10] Back in our component, we want to create an v-on or an @ to our component, buy tickets. We want to invoke a method when that happens. Let's just call it buyTickets for now. If we go back to main.js and define buyTickets, let's just console.log(Buy some tickets.). Let's check if that works OK. Buy some tickets.
[1:46] That's all well and good, but I would like some more information for my event. I would like to know, when I'm buying tickets, how many tickets to buy and what type of ticket I want to buy. I want to send some values. Let's send this.tickets toBuy and this.name. We're listing to buyTickets and we're triggering this function when that happens.
[2:15] The order that we parse them out is the order we can expect them. Number of tickets and name. Let's console.log that. Let's buy that number of that type of ticket. Check that's working OK, buy two bronze, hopefully, buy eight silver, buy 28 gold.
[2:51] We've got that event. Now, I would like to update the cart. If I update cart here, we can see we're updating by the number. We could, at this point, just this.cart is going to equal this.cart plus the number of tickets. If I buy two tickets, buy another three tickets, then I have five tickets.
[3:17] But we're losing the context. We don't know how many of each ticket we have. We might want to change updateCart to deal with that.