0
0
Vueframework~5 mins

v-on directive for events in Vue

Choose your learning style9 modes available
Introduction

The v-on directive lets you listen to user actions like clicks or key presses and run code when they happen.

When you want to run a function after a button is clicked.
When you need to respond to keyboard input in a form.
When you want to handle mouse movements or hover effects.
When you want to submit a form only after validating input.
When you want to toggle visibility of an element on user interaction.
Syntax
Vue
<element v-on:event="handlerFunction"></element>

You can shorten v-on: to just @ for cleaner code.

The event is the name of the user action like click or keyup.

Examples
Runs sayHello when the button is clicked.
Vue
<button v-on:click="sayHello">Click me</button>
Runs submitForm when the Enter key is pressed inside the input.
Vue
<input v-on:keyup.enter="submitForm">
Shortened syntax using @ to run showTooltip on mouse hover.
Vue
<div @mouseover="showTooltip">Hover me</div>
Sample Program

This Vue component shows a button that counts how many times it is clicked. Each click runs the incrementCount function, increasing the count.

Vue
<template>
  <button @click="incrementCount">Clicked {{ count }} times</button>
</template>

<script setup>
import { ref } from 'vue'
const count = ref(0)
function incrementCount() {
  count.value++
}
</script>
OutputSuccess
Important Notes

Always use functions or methods for event handlers to keep code organized.

You can listen to many event types like click, input, submit, and keyboard events.

Use modifiers like .prevent or .stop to control event behavior.

Summary

v-on listens to user actions and runs code when they happen.

You can use @ as a shortcut for v-on.

Event handlers help make your app interactive and responsive to users.