SyntaxStudy
Sign Up
Vue.js Event Handling with v-on
Vue.js Beginner 1 min read

Event Handling with v-on

The `v-on` directive (shorthand `@`) attaches event listeners to DOM elements. You can pass a method name, an inline handler, or a method call with arguments. Vue automatically calls `event.preventDefault()` or `event.stopPropagation()` for you when you append the `.prevent` or `.stop` event modifiers, keeping templates declarative and methods free of boilerplate. Key modifiers allow you to filter keyboard events without checking `event.key` manually: `@keyup.enter`, `@keyup.esc`, `@keydown.ctrl.s` and similar combinations are all built into the directive. Mouse button modifiers (`.left`, `.right`, `.middle`) and system key modifiers (`.ctrl`, `.alt`, `.shift`, `.meta`) can be chained as needed. The `.once` modifier ensures a listener fires only once and is then automatically removed. The `.passive` modifier hints to the browser that the handler will never call `preventDefault()`, enabling performance optimisations for scroll-intensive interfaces.
Example
<template>
  <!-- Inline handler -->
  <button @click="count++">Increment ({{ count }})</button>

  <!-- Method reference -->
  <button @click="resetCount">Reset</button>

  <!-- Method call with argument -->
  <button @click="addAmount(5)">Add 5</button>

  <!-- Accessing the native event -->
  <button @click="handleClick($event)">Log Event</button>

  <!-- Event modifiers -->
  <form @submit.prevent="onSubmit">
    <input @keyup.enter="onSubmit" v-model="inputVal" />
    <button type="submit">Submit</button>
  </form>

  <!-- Once modifier -->
  <button @click.once="initOnce">Initialize (once)</button>
</template>

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

const count    = ref(0);
const inputVal = ref('');

const resetCount  = () => { count.value = 0; };
const addAmount   = (n) => { count.value += n; };
const handleClick = (e) => { console.log(e.type, e.target); };
const onSubmit    = () => { console.log('Submitted:', inputVal.value); };
const initOnce    = () => { console.log('Runs only once'); };
</script>