Event Handling


Reminder: JavaScript Events

HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, it can "react" on these events.

A few common examples of events are clicking on a HTML element (such as a button), pressing a key, submitting a form, etc. 


Event Handling in VueJS

Vue has few handy directives for listening to common events. All Vue event directives start with "v-on:" and then the name of the event. For example:

  • v-on:click
  • v-on:submit
  • v-on:keydown 

The "@is a shortcut for "v-on:" which is shorter and easier to remember so that's what we're going to use from now:

  • @click
  • @submit
  • @keydown 

Let's begin by a simple click event example. First we use the @click directive on a button:

<button type="button" @click="alertMe">
I'll alert you after you click me!
</button>

And then define the alertMe() method to take care of the rest:

new Vue({
el: '#app',
methods: {
alertMe() {
alert('tada! it works!');
}
}
});

I used @click on a button, but it could be any other HTML element. It could be a <div>, <span>, <a>, <li>, etc. Yeah I'm sure you already knew this!


Events and v-model

v-model is once again your best friend while dealing with events. 

Let's say we need to add a few names entered in an input and display the list of the names:

<input type="text" v-model="name" placeholder="Enter the name...">

<button type="button" @click="addName">
Add
</button>
<ul>
<li v-for="item in list">{{ item }}</li>
</ul>
new Vue({
el: '#app',
data: {
name: null,
list: []
},
methods: {
addName() {
this.list.push(this.name); /* name added, now let's clear the input for next entry */
this.name = null;
}
}
});

Comments: