⚠️ This lesson is retired and might contain outdated information.

Handle DOM Events in Vue.js with v-on

Greg Thoman
InstructorGreg Thoman
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 8 months ago

v-on can be used to handle interaction with elements in your template. Modifiers like stop and prevent can be used in place to preventDefault() and stopPropagation. Vue.js can also capture key bindings such as v-on:keyup.enter and v-on:keyup.13.

[00:00] Here we have a button. Let's add v-on:click, and set that ="total += 1." Now, when we click the Add Dinosaur button, our total is incremented by one. We'll add an input field of type="number" and set v-model to the "amount" attribute on our component.

[00:17] Let's change our click event on the button to "addDinos". Now, we can type a number into the input field, and click the button to add that amount to our total. Let's change our button text to reflect the amount of Dinosaurs being added. We want to make it so that the user can just press enter from the input field, to add that amount of Dinosaurs.

[00:37] Let's add v-on:keyup.enter, and set it equal to "addDinos." Let's make this more accessible by wrapping these elements in a form element. On our form, let's add v-on:submit="add Dinos."

[00:53] We can remove the events from the button and the input field, since the form will be taking care of those. In order to prevent the default action of the form, we can use the event modifier prevent.

themathmagician
themathmagician
~ 6 years ago

What does the .prevent do, exactly? Why is it added in the end?

Jean-Francois
Jean-Francois
~ 6 years ago

If you run the code on CodeSandbox and remove the prevent modifier, you'll notice that the form submission causes a page reload.

Markdown supported.
Become a member to join the discussionEnroll Today