Vue v-on
Listen to DOM events and execute code
🎯 What is v-on?
The v-on directive attaches event listeners to elements. It listens for DOM events and runs JavaScript code when those events occur. You can use the shorthand @ symbol instead.
<!-- Full syntax -->
<button v-on:click="handleClick">Click</button>
<!-- Shorthand syntax -->
<button @click="handleClick">Click</button>
Output:
v-on Syntax Options
The v-on directive is flexible and powerful. You can use it with method names, inline expressions, or even pass arguments to your event handlers. The @ shorthand makes your code cleaner and is the preferred way to write event listeners in Vue applications.
Method Handler
Call a method by name
<button @click="greet">
Greet
</button>
Inline Handler
Execute code directly
<button @click="count++">
Add
</button>
With Arguments
Pass data to methods
<button @click="say('Hi')">
Say Hi
</button>
Event Object
Access event details
<button @click="handleEvent">
Event
</button>
🔹 Basic v-on Usage
Simple button click with method handler:
<template>
<div>
<button v-on:click="showMessage">Show Message</button>
<p v-if="visible">Hello from Vue!</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const visible = ref(false)
function showMessage() {
visible.value = true
}
</script>
Output:
🔹 Shorthand @ Syntax
Use @ as a shortcut for v-on (recommended):
<template>
<div>
<button @click="toggleTheme">Toggle Theme</button>
<p>Current theme: {{ theme }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const theme = ref('Light')
function toggleTheme() {
theme.value = theme.value === 'Light' ? 'Dark' : 'Light'
}
</script>
Output:
Current theme: Light
🔹 Inline Expressions
Execute simple code directly in the template:
<template>
<div>
<p>Counter: {{ counter }}</p>
<button @click="counter++">Increment</button>
<button @click="counter--">Decrement</button>
<button @click="counter = 0">Reset</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const counter = ref(0)
</script>
Output:
Counter: 0
🔹 Passing Arguments
Send data to your event handler methods:
<template>
<div>
<button @click="greet('Alice')">Greet Alice</button>
<button @click="greet('Bob')">Greet Bob</button>
<p>{{ greeting }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const greeting = ref('')
function greet(name) {
greeting.value = `Hello, ${name}!`
}
</script>
Output:
🔹 Accessing Event Object
Get information about the event using $event:
<template>
<div>
<button @click="handleClick($event)">Click Me</button>
<p>{{ eventInfo }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const eventInfo = ref('')
function handleClick(event) {
eventInfo.value = `Button clicked at X: ${event.clientX}, Y: ${event.clientY}`
}
</script>
Output: