Event handling

Vue · Essentials · 9 min

User interaction drives every app; modifiers remove most event boilerplate.

`v-on`, shortened to @, attaches a listener: @click="handler". The value can be:

  • A method name: @click="save" calls save(event) with the native event.
  • An inline statement: @click="count++" or @click="remove(item.id)". If you also need the event, pass the special $event variable: @click="remove(item.id, $event)".

Event modifiers handle common chores declaratively:

  • .prevent calls preventDefault(), e.g. @submit.prevent="onSubmit" stops the page reload.
  • .stop stops propagation; .self fires only if the event target is the element itself.
  • .once removes the listener after the first call; .passive marks scroll/touch listeners as passive; .capture uses the capture phase.

Key modifiers filter keyboard events: @keyup.enter="send", @keydown.esc="close", and combinations with system keys like @keyup.ctrl.enter. Add .exact to require exactly those modifiers. Mouse buttons have .left, .right and .middle.

Handlers are functions declared in <script setup>. Keep template statements short; once a handler does more than one thing, move it into a function. Vue removes listeners automatically when the component unmounts, so you never clean up template listeners yourself (only listeners you add manually with addEventListener).

Example

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

const message = ref('')
const log = ref([])

function send() {
  if (!message.value.trim()) return
  log.value.push(message.value)
  message.value = ''
}
function remove(i, event) {
  console.log('clicked', event.target.tagName); log.value.splice(i, 1)  // clicked BUTTON
}
</script>

<template>
  <form @submit.prevent="send">
    <input v-model="message" @keydown.esc="message = ''">
    <button>Send</button>
  </form>
  <p v-for="(m, i) in log" :key="i">
    {{ m }} <button @click="remove(i, $event)">x</button>
  </p>
</template>

Remember

  • @event="method" or an inline statement; use $event for the native event
  • .prevent, .stop, .once, .self replace manual event-object calls
  • Key modifiers like @keyup.enter filter keyboard events

Watch out for

  • Forgetting .prevent on a form's submit so the browser reloads the page.

Check yourself

  1. What does `@submit.prevent="save"` do?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: vuejs.org/guide/essentials/event-handling.html