Event handling and modifiers

Beginner · 7 min

Listening to DOM events with v-on, method versus inline handlers, the $event variable, and the event, key and mouse modifiers that cut handler boilerplate.

Before thisText interpolation and attribute binding

Vue School · 72 min · from 25:33

Event handling and modifiers

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Vue SchoolReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `v-on:click="handler"`, written `@click="handler"`, attaches a native DOM event listener, and there is nothing to clean up by hand when the element goes away.
  • A handler can be a method name, which receives the native event, or an inline statement like `count++` or `remove(item.id)`. In an inline handler the event is available as `$event`.
  • Event modifiers such as `.prevent`, `.stop`, `.self`, `.once`, `.capture` and `.passive` replace `event.preventDefault()` style boilerplate, and chaining order matters when you combine them.
  • Key modifiers filter keyboard events by `event.key` in kebab-case, for example `@keyup.enter` or `@keydown.page-down`, with aliases for common keys like `.esc`, `.space` and `.delete`.
  • System modifiers `.ctrl`, `.alt`, `.shift` and `.meta` require that key to be held, `.exact` rules out any extra modifier keys, and `.left`, `.right` and `.middle` filter mouse buttons.
  • Unlike React, Vue does not wrap events in a synthetic event system. Handlers receive the browser's own `Event` objects.

Listening without the bookkeeping

In plain JavaScript, reacting to a click means finding the element, calling addEventListener, and remembering to call removeEventListener when the element is removed, or you leak the listener. DOM manipulation and events covers that model, including bubbling and capture. In a component, elements come and go as state changes, and doing that bookkeeping by hand for every button would be exhausting.

v-on declares the listener on the element in the template. Vue attaches it when the element is created, and the listener goes away with the element, so there is no cleanup to remember.

<script setup>
import { ref } from 'vue'

const count = ref(0)

function increment() {
  count.value++
}
</script>

<template>
  <button v-on:click="increment">Add</button>
  <button @click="increment">Add (shorthand)</button>
  <p>Clicked {{ count }} times</p>
</template>

@ is short for v-on:, just as : is short for v-bind:, and almost all Vue code uses it. The part after the @ is any DOM event name: click, input, submit, keydown, mouseover, scroll.

Method handlers and inline handlers

The value of @click can take two forms, and Vue’s compiler tells them apart by looking at it.

If the value is a function name or a property path like increment or actions.save, it is a method handler. Vue calls the function and passes the native event:

<script setup>
function logTarget(event) {
  console.log(event.target.tagName) // "BUTTON"
}
</script>

<template>
  <button @click="logTarget">Inspect</button>
</template>

Anything else is an inline handler: a JavaScript statement Vue runs when the event fires. Inline handlers are how you pass arguments:

<template>
  <button @click="count++">Add</button>
  <li v-for="item in items" :key="item.id">
    {{ item.label }}
    <button @click="remove(item.id)">Remove</button>
  </li>
</template>

Inside an inline handler the native event is not passed automatically, because you are writing the call yourself. When you need it alongside your own arguments, Vue exposes it as the special variable $event, or you can write an arrow function:

<button @click="warn('Not saved yet', $event)">Submit</button>
<button @click="(event) => warn('Not saved yet', event)">Submit</button>

The event is the real event

React passes handlers a SyntheticEvent, a cross-browser wrapper, and attaches its listeners at the root of the app. Vue does neither. A listener declared with @click is attached directly to that element with addEventListener, and the handler receives the browser’s own MouseEvent, KeyboardEvent, SubmitEvent and so on. Everything you know about native events, including how they bubble, applies unchanged. Handling events in React is the comparison point.

Event modifiers

A remarkable share of handler code is housekeeping: call preventDefault(), call stopPropagation(), check that the click was not on a child. Modifiers move that housekeeping into the template, so the handler can be pure logic. They are suffixes after a dot:

<!-- calls event.preventDefault(), so the page does not reload -->
<form @submit.prevent="onSubmit">...</form>

<!-- calls event.stopPropagation(), so parent listeners do not fire -->
<button @click.stop="toggleFavourite">♥</button>

<!-- runs only if the click was on the overlay itself, not on the dialog inside it -->
<div class="overlay" @click.self="close">
  <div class="dialog">...</div>
</div>

<!-- removes itself after the first trigger -->
<button @click.once="claimReward">Claim</button>

<!-- listens in the capture phase instead of the bubble phase -->
<div @click.capture="logEveryClick">...</div>

<!-- tells the browser the handler will never call preventDefault() -->
<div @scroll.passive="onScroll">...</div>

A modifier can stand alone without a handler, as in <form @submit.prevent>, when all you want is the default action blocked.

Modifiers chain, and they run in the order written. @click.prevent.self blocks the default action of every click on the element and its children but runs the handler only for direct clicks. @click.self.prevent checks .self first, so clicks on children are left completely alone.

.passive exists for scroll and touch performance: the browser can scroll immediately instead of waiting to see whether your handler cancels the event. That makes it the opposite of .prevent. Do not combine them: the browser ignores the .prevent and will likely log a warning.

Key modifiers

Keyboard listeners almost always care about one specific key. Instead of checking event.key inside the handler, put the key in the modifier:

<input @keyup.enter="addItem" @keyup.esc="cancelEdit" />
<div @keydown.page-down="nextPage" tabindex="0">...</div>

Any valid KeyboardEvent.key value works, converted to kebab-case, so PageDown becomes .page-down. Vue also provides aliases for the most common keys: .enter, .tab, .delete (which matches both Delete and Backspace), .esc, .space, .up, .down, .left and .right.

System keys, exact matches and mouse buttons

The system modifiers .ctrl, .alt, .shift and .meta (Command on macOS, the Windows key on Windows) mean “only while this key is held”:

<input @keydown.ctrl.enter="send" />
<div @click.shift="extendSelection">...</div>

On keyup, a system modifier has to be held at the moment another key is released. @keyup.ctrl does not fire when you release Control on its own.

System modifiers match even if other modifiers are also held: @click.ctrl fires for Ctrl+click and for Ctrl+Shift+click. Add .exact to require exactly the listed modifiers and nothing more:

<!-- only Ctrl+click, not Ctrl+Shift+click -->
<button @click.ctrl.exact="onCtrlClick">A</button>

<!-- only a click with no modifier keys at all -->
<button @click.exact="onPlainClick">B</button>

For mouse events, .left, .right and .middle restrict the handler to a particular button, so @mousedown.right responds only to right-clicks.

What the video covers

The embed is a seven-minute stretch of Vue School’s Vue Fundamentals with the Composition API course from May 2024, made of three consecutive chapters: handling user events with v-on, keyboard modifiers, and form submission events. It was chosen over Vue Mastery’s event-handling lesson, linked below, because that lesson does not cover modifiers at all, and modifiers are half of this topic. The course writes a setup() function in a browser build rather than <script setup>; the template side is identical. The clip uses a handful of modifiers in context but does not go through the full set, so .self, .capture, .passive, chaining order, .exact and the mouse-button modifiers are covered here.

Where this fits

@ also listens to events that child components emit, using the same syntax and some of the same modifiers. That is the subject of component events and emits. The next lesson combines a binding and a listener into one directive: form input bindings with v-model.

Check yourself

  1. 01What is the difference between `@click="save"` and `@click="save()"`?

    `@click="save"` is a method handler: Vue calls `save` with the native click event as its argument. `@click="save()"` is an inline handler: Vue runs that statement on click, so `save` is called with no arguments. To pass the event to an inline call, use `save($event)`.

  2. 02How do you stop a form submission from reloading the page in Vue without writing `event.preventDefault()`?

    Use the `.prevent` modifier on the submit listener: `<form @submit.prevent="onSubmit">`. Vue calls `preventDefault()` for you before running the handler.

  3. 03What is the difference between `@click.prevent.self` and `@click.self.prevent`?

    Modifiers apply in the order written. `.prevent.self` prevents the default action for every click, including clicks on child elements, and runs the handler only when the element itself was clicked. `.self.prevent` checks `.self` first, so both the prevention and the handler only apply to clicks on the element itself.

  4. 04You want Ctrl+Enter to send a message but plain Enter and Ctrl+Shift+Enter to do nothing. What listener do you write?

    `@keydown.ctrl.enter.exact="send"` on the input. `.enter` matches the key, `.ctrl` requires Control to be held, and `.exact` rejects the event if any other system modifier, such as Shift, is also held.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark