Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Handle DOM Events in Vue.js with v-on

    Greg ThomanGreg Thoman

    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.

    vueVue.js
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss