Respond to Events with the v-on (@) Directive in Vue

Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated a year ago

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.

egghead
egghead
~ 16 seconds ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today