LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1015 min read

Event Handling

Respond to user interaction using the v-on directive, inline handlers, methods, and event modifiers.

Listening to Events with v-on

The v-on directive (shorthand: @) attaches an event listener to an element, running an expression or method when that event fires.

<template>
<button v-on:click="count++">Add (long form)</button>
<button @click="count++">Add (shorthand)</button>
</template>

Inline Handlers vs Method Handlers

A short expression can live directly in the template. Anything more involved should call a named function defined in <script setup>.

<script setup>
import { ref } from 'vue';
const count = ref(0);
function increment() {
count.value++;
console.log('Count is now', count.value);
}
</script>
<template>
<button @click="increment">Add</button>
</template>

Accessing the Event Object

A method handler automatically receives the native DOM event as its argument. When calling a method with your own arguments, pass the special $event variable to still access it.

<script setup>
function logInput(event) {
console.log(event.target.value);
}
function warn(message, event) {
console.log(message, event.target.tagName);
}
</script>
<template>
<input @input="logInput" />
<button @click="warn('Clicked!', $event)">Click</button>
</template>

Event Modifiers

Vue provides modifiers — chained after the event name with a dot — that handle common needs like preventDefault() and stopPropagation() declaratively, without cluttering your method with DOM API calls.

ModifierEquivalent To
.preventevent.preventDefault()
.stopevent.stopPropagation()
.onceThe listener triggers at most one time
.selfOnly triggers if the event target is the element itself, not a child
<form @submit.prevent="handleSubmit">
<button type="submit">Save</button>
</form>

Key Modifiers

For keyboard events, Vue offers key modifiers so you don't need to manually check event.key inside your handler.

<input @keyup.enter="submitForm" />
<input @keyup.esc="clearInput" />

FAQs

Yes — e.g. @click.stop.prevent applies both stopPropagation and preventDefault, in the order they're written.

Conceptually similar, but v-on is managed by Vue's reactivity and cleanup system, and supports modifiers and method references cleanly, unlike a raw inline onclick attribute.

Summary

v-on (or @) attaches event listeners, with modifiers covering the most common needs declaratively. Next, you'll build two-way binding for form inputs with v-model.

Next Lesson →

Forms & v-model