An interface does not just display data: it responds to what the user does. Every click, every key press and every form submission is a browser event, and Vue provides the v-on directive (shortened to @) to listen for them declaratively, directly in the template. So far you have used it in its simplest form, @click="fn". In this lesson you will see everything it can do: inline and named handlers, access to the native event object, passing arguments and, above all, modifiers, which solve in a single word tasks as common as stopping a form from reloading the page or reacting only to the Enter key. In Colmena Bookings we will tidy up the booking buttons, make the search box filter when Enter is pressed and clear with Escape, and ask for confirmation before cancelling.

Contents

  1. v-on and its @ shorthand
  2. Inline handlers versus named handlers
  3. Accessing the native event
  4. Passing arguments to the handler
  5. Event modifiers
  6. The order of modifiers matters
  7. Key modifiers
  8. System keys, .exact and mouse button modifiers
  9. How to name handlers
  10. Case study: booking, releasing, searching and cancelling in Colmena

  1. v-on and its @ shorthand

The v-on directive registers an event listener on an element. Its argument is the name of the DOM event and its value is what should run:

<button v-on:click="bookSeats(1)">Book a seat</button>

<!-- Usual shorthand -->
<button @click="bookSeats(1)">Book a seat</button>

It works for any DOM event: click, dblclick, input, change, submit, keydown, keyup, focus, blur, mouseenter, scroll... The name is the same one you would use with addEventListener, without the on prefix.

Advantages over adding listeners by hand with addEventListener:

  • It is declarative: reading the template, you can see what each element does.
  • Vue removes them automatically when the element or component disappears. There are no memory leaks from forgotten listeners (unlike the setInterval in ReceptionClock, which we had to clean up by hand).
  • The handler has direct access to the component's state.

  1. Inline handlers versus named handlers

The value of v-on can be written in two ways.

2.1 Inline handler

This is JavaScript code that runs as it is when the event occurs. Useful for one-line actions:

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

const showClock = ref(true)
const attendees = ref(0)
</script>

<template>
  <button @click="showClock = !showClock">Show/hide clock</button>
  <button @click="attendees++">+ Attendee</button>
</template>

Notice something important: in the Template Syntax lesson we saw that interpolations do not accept assignments. v-on is the exception: its value is the body of a function that Vue creates for you, so it accepts assignments (showClock = !showClock), increments and even several statements separated by semicolons (@click="bookSeats(1); logAction()"). And, as in the rest of the template, refs are used without .value.

2.2 Named handler (method)

This is the name of a function in the component, without parentheses:

<script setup>
function toggleClock() {
  showClock.value = !showClock.value
}
</script>

<template>
  <button @click="toggleClock">Show/hide clock</button>
</template>

Vue will call toggleClock when the click occurs and pass it the event object as the first argument.

2.3 How Vue tells them apart

The compiler looks at the shape of the value: if it is a name or a property path (toggleClock, actions.book), it treats it as a named handler; if it is anything else (toggleClock(), attendees++), as inline code.

Form Example Type Receives the event
Function name @click="toggleClock" Named Yes, as the first parameter
Call with parentheses @click="bookSeats(1)" Inline Only if you pass it with $event
Expression or assignment @click="attendees++" Inline Available as $event
Arrow function @click="(e) => bookSeats(1, e)" Inline (it is a function) Yes, as the arrow function's parameter

Recommendation: use inline handlers only for trivial one-line actions; for everything else, a named function in the script. Logic in the script can be read, reused and tested; logic hidden in attributes cannot.

  1. Accessing the native event

Sometimes you need information from the event itself: which key was pressed, whether the Shift key was held down, which element triggered it, the text in a field... There are two ways to get the native event object (the same Event you would receive with addEventListener).

With a named handler, it arrives as the first parameter:

<script setup>
function onBookClick(event) {
  console.log(event.type)      // 'click'
  console.log(event.target)    // the <button> that was clicked
  console.log(event.shiftKey)  // true if the Shift key was held down
}
</script>

<template>
  <button @click="onBookClick">Book a seat</button>
</template>

In an inline handler, through the special $event variable:

<input @input="console.log($event.target.value)" />
<button @click="logClick('book', $event)">Book</button>

$event only exists inside v-on inline handlers. You already saw it in the expansion of v-model in the previous lesson: @input="search = $event.target.value".

Event properties you will use often:

Property What it contains
event.type The event name ('click', 'keyup'...)
event.target The element where the event originated (it may be a child)
event.currentTarget The element that has the listener
event.target.value The current value of a form field
event.key The key pressed in keyboard events ('Enter', 'Escape', 'a'...)
event.shiftKey, ctrlKey, altKey, metaKey Whether each system key was held down
event.preventDefault() Cancels the browser's default action
event.stopPropagation() Stops the event from continuing to bubble up to parent elements

  1. Passing arguments to the handler

To reuse a function with different values, call it with parentheses in an inline handler:

<script setup>
function bookSeats(count) {
  console.log(`Booking ${count} seats`)
}
</script>

<template>
  <button @click="bookSeats(1)">+1 seat</button>
  <button @click="bookSeats(4)">+4 seats</button>
</template>

If you also need the event, pass it explicitly with $event (by convention, last):

<script setup>
function bookSeats(count, event) {
  if (event?.altKey) {
    console.log('Booking with Alt: extra confirmation could be requested')
  }
  console.log(`Booking ${count} seats`)
}
</script>

<template>
  <button @click="bookSeats(4, $event)">+4 seats</button>
</template>

A common mistake is writing @click="bookSeats" and expecting count to have a value: in that case Vue passes the event as the first argument, and count would be a PointerEvent object.

  1. Event modifiers

In handlers it is very common to call event.preventDefault() or event.stopPropagation(). Vue lets you do this without cluttering your functions, using modifiers: dot-prefixed suffixes after the event name.

Modifier Equivalent to / effect Typical example
.prevent event.preventDefault() @submit.prevent: stopping a form from reloading the page
.stop event.stopPropagation() A button inside a clickable card: the click should not reach the card
.self Only runs the handler if event.target is the element itself (not a child) Closing a modal when the backdrop is clicked, but not its content
.once The handler runs at most once Showing a welcome message only the first time
.capture Listens in the capture phase (from parent to child) instead of the bubbling phase The parent must find out before the children
.passive Registers the listener as passive: it promises not to call preventDefault @scroll.passive, @touchmove.passive: improves scrolling smoothness on mobile devices

Let's look at the most commonly used ones with Colmena examples.

.prevent on a form. By default, submitting a <form> reloads the page, which in an SPA would wipe everything out:

<form @submit.prevent="applySearch">
  <input v-model="searchText" />
  <button>Search</button>
</form>

The modifier can be used without a handler: <form @submit.prevent> simply prevents the submission. Complete forms are covered in Forms with v-model.

.stop on a button inside a clickable card:

<article class="card" @click="showDetail">
  <h2>Panal Room</h2>
  <!-- Without .stop, clicking the button would also open the detail -->
  <button @click.stop="markFavorite">☆ Favourite</button>
</article>

DOM events bubble: a click on the button reaches the button first and then each of its ancestors. .stop cuts that journey short.

.self on a modal window's backdrop:

<div class="modal-backdrop" @click.self="closeModal">
  <div class="modal">
    <!-- Clicking in here does NOT close the modal: the target is a child -->
    <p>Are you sure you want to cancel the booking?</p>
  </div>
</div>

.once:

<button @click.once="showRules">Read the room usage rules</button>

After the first click, Vue removes the listener.

.passive must not be combined with .prevent: a passive listener cannot cancel the default action, and the browser will ignore the preventDefault (and show a warning).

  1. The order of modifiers matters

Modifiers can be chained: @click.stop.prevent="...". Vue applies them in the order you write them, and in some combinations that changes the result. The classic case is .prevent with .self:

<!-- A: prevents the default action on ALL clicks (on the element and on its children)
        and only runs the handler if the click was on the element itself -->
<div @click.prevent.self="close">...</div>

<!-- B: only prevents (and runs) if the click was on the element itself;
        clicks on the children pass through untouched -->
<div @click.self.prevent="close">...</div>
flowchart TB
    subgraph A["@click.prevent.self"]
        A1["Click (on the div or on a child)"] --> A2[".prevent: preventDefault() always"]
        A2 --> A3{".self: is the target the div?"}
        A3 -->|"Yes"| A4["Runs close"]
        A3 -->|"No"| A5["Stops"]
    end
    subgraph B["@click.self.prevent"]
        B1["Click (on the div or on a child)"] --> B3{".self: is the target the div?"}
        B3 -->|"Yes"| B2[".prevent and runs close"]
        B3 -->|"No"| B5["Stops without touching anything"]
    end

If there were a link inside the div, with variant A the link would stop working (its navigation is prevented); with variant B, it would work. Think of modifiers as a chain of filters that runs from left to right: each one can act on the event or stop the chain.

  1. Key modifiers

In keyboard events (keyup, keydown), Vue lets you filter by key with a modifier:

<input @keyup.enter="applySearch" @keyup.esc="clearSearch" />

It is equivalent to checking event.key by hand, but much more readable:

// What you save yourself
function onKeyUp(event) {
  if (event.key === 'Enter') applySearch()
  else if (event.key === 'Escape') clearSearch()
}

Key aliases that Vue provides:

Modifier Key
.enter Enter
.tab Tab
.delete Delete and Backspace
.esc Escape
.space Space bar
.up, .down, .left, .right Arrow keys

In addition, you can use any key name from KeyboardEvent.key converted to kebab-case: @keyup.page-down (the PageDown key), @keydown.f1, @keyup.a.

keyup or keydown? keydown fires when the key is pressed (and repeats if you hold the key down); keyup fires when it is released, only once. For actions such as "apply search", keyup avoids repetitions. For shortcuts that must cancel the browser's action (such as preventing Tab from moving the focus), you need keydown, because by keyup the action has already happened.

  1. System keys, .exact and mouse button modifiers

8.1 System keys

The .ctrl, .alt, .shift and .meta modifiers (the ⌘ key on a Mac or the ⊞ Windows key on a PC) require that key to be held down at the moment of the event. They can be combined with keyboard and mouse events:

<!-- Ctrl + Enter in the search box -->
<input @keyup.ctrl.enter="searchAllFloors" />

<!-- Alt + click -->
<button @click.alt="bookSeats(5)">Book a seat</button>

One detail: with keyup, the system key must still be held down while you release the other one. Releasing only Ctrl does not trigger @keyup.ctrl.

8.2 .exact: exactly those keys

Without .exact, @click.ctrl also fires with Ctrl + Shift + click. To require an exact combination:

<!-- Fires with Ctrl + click, but NOT with Ctrl + Shift + click -->
<button @click.ctrl.exact="selectMultiple">Select</button>

<!-- Only with a click WITHOUT any system key -->
<button @click.exact="selectOne">Select</button>

8.3 Mouse button modifiers

.left, .right and .middle restrict the handler to a specific mouse button:

<!-- Right-click: our own context menu instead of the browser's -->
<article @click.right.prevent="openRoomMenu">Panal Room</article>

Use them sparingly: many users do not know there is a special right-click, and touch screens have no mouse buttons. Every important action should also be available through a visible button.

  1. How to name handlers

A good name makes the template read like a sentence. Recommendations:

Situation Pattern Colmena examples
The function performs a business action, independent of the event A verb that describes what it does bookSeats, releaseSeats, applySearch, nextRoom
The function needs the event or decides what to do based on it on + element + event onBookClick(event), onKeyUp(event)
Avoid Generic names that only say when it runs handleClick, onClick, function1

The advantage of naming by action is that the same function can be called from several places (a button, a keyboard shortcut, a watcher) and its name is still correct. on... names reveal that the function is an "adapter" between an event and the logic, and they are usually short: they read the event and call action functions.

  1. Case study: booking, releasing, searching and cancelling in Colmena

Let's tidy up App.vue. At the end of lesson 02-02, the old "Book a room" button, which only decremented a counter, sat alongside the new "Book a seat" one. Now:

  • We remove bookRoom() and its button: the freeRooms counter stays purely as information (in the next lesson it will be calculated automatically).
  • Booking and releasing seats become functions with an argument; Shift + click will book 5 seats in one go.
  • Cancelling all the seats will ask for confirmation.
  • The search box separates what is being typed (searchText) from the applied search (search): it is applied with Enter and cleared with Escape. We also bring in the normalize function from exercise 3 of the previous lesson.

10.1 The script

Replace the <script setup> of src/App.vue with this one:

<script setup>
import { ref, reactive } from 'vue'
import ReceptionClock from './components/ReceptionClock.vue'
import RoomCard from './components/RoomCard.vue'
import { rooms } from './data/rooms.js'

// Data that does not change
const totalRooms = rooms.length
const today = new Date()
const receptionNote = 'The <strong>Néctar Room</strong> closes at 18:00 today.'

// Header state
const freeRooms = ref(rooms.filter((room) => room.available).length)
const showClock = ref(true)

// --- Selected room and seats ---
const selectedRoom = ref(rooms[0])
const seats = reactive({ booked: 0 })

function nextRoom() {
  const index = rooms.findIndex((room) => room.id === selectedRoom.value.id)
  selectedRoom.value = rooms[(index + 1) % rooms.length]
  seats.booked = 0
}

function bookSeats(count) {
  const free = selectedRoom.value.capacity - seats.booked
  seats.booked += Math.min(count, free) // never more than are left
}

function releaseSeats(count) {
  seats.booked = Math.max(0, seats.booked - count) // never below 0
}

// Adapter between the event and the action: Shift + click books 5 seats
function onBookClick(event) {
  bookSeats(event.shiftKey ? 5 : 1)
}

function cancelSeats() {
  const confirmed = window.confirm(
    `Cancel the ${seats.booked} seats booked in the ${selectedRoom.value.name}?`
  )
  if (confirmed) {
    seats.booked = 0
  }
}

// --- Search ---
const searchText = ref('') // what the user is typing (v-model)
const search = ref('')     // the search applied when Enter is pressed
const placeholder = 'Search by name and press Enter'

function normalize(text) {
  return text
    .normalize('NFD')
    .replace(/[̀-ͯ]/g, '')
    .trim()
    .toLowerCase()
}

function matchesSearch(room) {
  return normalize(room.name).includes(normalize(search.value))
}

function applySearch() {
  search.value = searchText.value
}

function clearSearch() {
  searchText.value = ''
  search.value = ''
}

// --- Utilities ---
function formatDate(date) {
  return date.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' })
}

function toggleClock() {
  showClock.value = !showClock.value
}
</script>

Details to note:

  • bookSeats(count) works out the free seats and adds at most that many: if 3 are left and you ask for 5, it books 3. This way the function is safe even if it is called from a keyboard shortcut or from a button that has been enabled by mistake.
  • onBookClick(event) is an adapter: it reads event.shiftKey and delegates to bookSeats. The business logic knows nothing about events.
  • window.confirm(...) shows the browser's native dialog and returns true or false. We call it from the script (it would not be accessible in the template: window is not on the allowlist). It is a temporary solution; in module 3 we will create our own BaseModal with slots.
  • The search box has two refs: searchText changes on every keystroke; search only when the user confirms. This avoids recalculating results with every letter and is a common pattern in search boxes that query a server.

10.2 The template

Replace the contents of <main>:

<main class="content">
  <p class="note" v-html="receptionNote"></p>
  <p>
    <strong>{{ freeRooms }}</strong>
    {{ freeRooms === 1 ? 'free room' : 'free rooms' }} out of {{ totalRooms }}
  </p>
  <button class="button" @click="toggleClock">Show/hide clock</button>

  <div class="search-box">
    <label for="search">Search rooms</label>
    <input
      id="search"
      v-model="searchText"
      type="search"
      :placeholder
      @keyup.enter="applySearch"
      @keyup.esc="clearSearch"
    />
    <button class="button" :disabled="searchText === ''" @click="clearSearch">Clear</button>
    <p>
      Applied search: "{{ search }}" ·
      {{ matchesSearch(selectedRoom) ? 'the selected room matches' : 'the selected room does not match' }}
    </p>
  </div>

  <section class="selection">
    <h2>Selected room: {{ selectedRoom.name }}</h2>
    <p>Floor {{ selectedRoom.floor }} · up to {{ selectedRoom.capacity }} people</p>
    <p>Booked seats: {{ seats.booked }} / {{ selectedRoom.capacity }}</p>

    <button
      class="button"
      :disabled="!selectedRoom.available || seats.booked >= selectedRoom.capacity"
      :title="selectedRoom.available ? 'Shift + click: books 5 seats' : 'Room under maintenance'"
      @click="onBookClick"
    >
      Book a seat
    </button>
    <button class="button" :disabled="seats.booked === 0" @click="releaseSeats(1)">
      Release a seat
    </button>
    <button class="button" :disabled="seats.booked === 0" @click="cancelSeats">
      Cancel booking
    </button>
    <button class="button" @click="nextRoom">Next room</button>
  </section>

  <RoomCard />
</main>

Try it all out:

  1. Click "Book a seat": it adds 1. Hold Shift and click: it adds 5 (or however many are left). In the Celda Booth, it never goes above 1.
  2. "Release a seat" subtracts 1 and is disabled when it reaches 0.
  3. "Cancel booking" shows the dialog; if you choose "Cancel" in the dialog, nothing happens.
  4. Type "polen" in the search box: the applied search does not change until you press Enter. Press Escape: both the field and the search are cleared.

The handlers deliberately mix styles: @click="onBookClick" (named, receives the event), @click="releaseSeats(1)" (inline, with an argument) and @keyup.enter="applySearch" (named, with a modifier). They all call functions in the script; none of them hides logic in the template.

Common Mistakes and Tips

  • Calling the function when registering the handler. @click="bookSeats" is correct and so is @click="bookSeats(1)", but in plain JavaScript addEventListener('click', bookSeats(1)) would run the function on the spot. In Vue this does not happen because the compiler wraps inline code in a function; do not carry this habit over to the script.
  • Expecting an argument with a named handler. @click="releaseSeats" passes the event as count, and seats.booked - event gives NaN.
  • Using $event outside v-on. It only exists in inline handlers.
  • Forgetting .prevent on forms. The page reloads and you lose all the state. If you see the application "flicker" when submitting, this is why.
  • Chaining modifiers without thinking about the order. .prevent.self and .self.prevent are not the same.
  • Combining .passive with .prevent. The browser ignores preventDefault in passive listeners.
  • Relying only on the keyboard or only on the mouse. Always provide a visible button for actions (such as "Clear") as well as the shortcut (Escape).
  • Tip: if an inline handler starts to grow (a ternary, two calls...), move it into a named function. The template should say what happens; the script, how.

Exercises

Exercise 1. Add a shortcut to the search box in App.vue: with the focus on the field, Alt + down arrow must move to the next room without the browser doing anything else (in some browsers, Alt + down arrow opens the field's history). Should you use keyup or keydown? Why?

Exercise 2. In RoomCard.vue, make a double click on the <h2> title reset the attendees to 0, and make the "+ Attendee" and "− Attendee" buttons respond only to a click without any system keys held down.

Exercise 3. You have this markup for a future confirmation window. The requirement is that clicking the dark backdrop closes it, that clicks inside the white box do not close it, and that the "Cancellation policy" link keeps working. Choose the appropriate modifiers and justify your choice.

<div class="modal-backdrop" @click="closeModal">
  <div class="modal">
    <p>Cancel the booking?</p>
    <a href="/cancellation-policy.pdf">Cancellation policy</a>
    <button @click="confirmCancellation">Yes, cancel</button>
  </div>
</div>

Solutions

Solution 1.

<input
  id="search"
  v-model="searchText"
  type="search"
  :placeholder
  @keyup.enter="applySearch"
  @keyup.esc="clearSearch"
  @keydown.alt.down.prevent="nextRoom"
/>

It must be keydown: the browser's default action happens when the key is pressed, so to cancel it with .prevent you have to step in on keydown. On keyup it would already be too late. .alt.down requires Alt to be held down together with the down arrow; nextRoom is a named handler (it will receive the event, but does not use it).

Solution 2.

<h2 @dblclick="attendees = 0">{{ room.name }}</h2>
<!-- ... -->
<button :disabled="attendees === 0" @click.exact="removeAttendee">− Attendee</button>
<button
  :disabled="!room.available || full"
  :title="room.available ? null : 'Room unavailable'"
  @click.exact="addAttendee"
>
  + Attendee
</button>
  • @dblclick="attendees = 0" is a trivial assignment: an inline handler is acceptable. The existing watch(full) will clear the notice automatically if the room was full.
  • @click.exact with no other modifiers only runs if no system key is held down.

Solution 3.

<div class="modal-backdrop" @click.self="closeModal">
  <div class="modal">
    <p>Cancel the booking?</p>
    <a href="/cancellation-policy.pdf">Cancellation policy</a>
    <button @click="confirmCancellation">Yes, cancel</button>
  </div>
</div>
  • .self on the backdrop: clicks on the white box, the paragraph, the link or the button have those children as their target, not the backdrop, so closeModal does not run.
  • We do not add .prevent: if we wrote @click.prevent.self, the preventDefault would be applied to every click that bubbles up to the backdrop, including the one on the link, which would stop opening. @click.self.prevent would be harmless, but unnecessary: a div has no default action.
  • Valid alternative: @click="closeModal" on the backdrop and @click.stop on the .modal box. It works, but .stop prevents any listener higher up from finding out about the inner clicks, which can break other features (analytics, for example). .self is more precise.

Conclusion

v-on (or @) listens for any DOM event. Its value can be a named handler, which receives the native event as its first parameter, or inline code, which accepts assignments, arguments and the $event variable. Modifiers replace the repetitive code in handlers: .prevent, .stop, .self, .once, .capture and .passive for the event's behaviour; .enter, .esc, .tab and company for the keyboard; .ctrl, .alt, .shift, .meta and .exact for combinations; and .left, .right and .middle for the mouse, always bearing in mind that they are applied in the order written. You have also seen that naming handlers after the action they perform keeps the template readable. Colmena Bookings books and releases seats within limits, supports Shift + click, asks for confirmation before cancelling and has a search box that is applied with Enter and cleared with Escape.

App.vue is starting to accumulate values that are derived from others (the free rooms, whether the selected room matches the search, how many seats are left), which we calculate with functions called on every render. In the next lesson, Computed Properties and Watchers, you will learn to declare them efficiently with computed and to react to changes with watch, including loading rooms from a simulated API.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved