Episode 5 of 44

Events

Handle DOM events in Vue with v-on — respond to clicks, hovers, double-clicks, and pass event data to methods.

Events

Vue makes handling DOM events simple with the v-on directive. In this episode you will learn how to listen for clicks, mouse events, and other interactions, and respond by calling methods.

The v-on Directive

<div id="app">
    <h1>{{ age }}</h1>
    <button v-on:click="age++">Add a Year</button>
    <button v-on:click="age--">Subtract a Year</button>
</div>

v-on:click listens for a click event. The value can be an inline expression (age++) or a method name.

Shorthand

<!-- Full syntax -->
<button v-on:click="doSomething">Click</button>

<!-- Shorthand (@ symbol) -->
<button @click="doSomething">Click</button>

Calling Methods on Events

<button @click="add(1)">Add 1</button>
<button @click="add(10)">Add 10</button>
<button @dblclick="add(1)">Double-click to Add</button>

methods: {
    add(years) {
        this.age += years;
    }
}

Common Events

EventVue SyntaxTriggers When
Click@clickElement is clicked
Double-click@dblclickElement is double-clicked
Mouse enter@mouseenterMouse enters the element
Mouse leave@mouseleaveMouse leaves the element
Mouse move@mousemoveMouse moves over the element

The Event Object

<div @mousemove="updateCoords">{{ x }}, {{ y }}</div>

methods: {
    updateCoords(e) {
        this.x = e.offsetX;
        this.y = e.offsetY;
    }
}

Vue automatically passes the native DOM event object to the method. Access properties like e.target, e.offsetX, e.type, etc.

Key Takeaways

  • v-on:event (or @event) listens for DOM events
  • You can run inline expressions or call methods with arguments
  • Vue passes the DOM event object to the method automatically
  • Common events: @click, @dblclick, @mouseenter, @mousemove