We'll see how we can respond to HTML events using the v-on
directive. We'll discuss how v-on
can be abbreviated to @
in our HTML and look at some of the events that are available to us.
In this lesson, we'll create a button that adds tickets to our cart.
Instructor: [0:00] Let's add a cart into our application to keep track of tickets that have been purchased. At the moment, I've got here. Let's instead add a data prop for our cart. Let's set that to . Then, back in our application, let's get our cart value out. If we open our DevTools, we can see cart , as we change the cart value in our dev tools, it's being updated in our browser.
[0:24] What I'd like to do is to add a button that's going to add the ticket. Every time I click this button, I would like the cart to increase by 1. Vue, unsurprising, has a directive for that, it's called v-on -- v-on: and then the event. Vue maps most of the browser events here, including click, so v-on:click. Let's do something. Again, in quotes we're going to pass any JavaScript statement.
[0:48] I want to add 1 to the cart. To do that, I just do cart++, which is the JavaScript method to increment a variable by 1. Let's save this and see what happens if I click. As I click, we can see our cart's increasing as I click it.
V-on: [1:04] Is used quite a lot. Much the same way that we are able to swap out v-bind for just a colon, we can replace v-on: with the character @, carries out the same behavior. It's still true that when I press the button, this @click is equivalent to v-on:click, and we're incrementing the cart variable by 1.