How to Use v-on in Vue: Event Handling Made Simple
In Vue, use the
v-on directive to listen for DOM events like clicks and run JavaScript code or methods when they happen. You write v-on:eventName="handlerMethod" or use the shorthand @eventName="handlerMethod" to bind event listeners easily.Syntax
The v-on directive listens for events on elements. Its basic syntax is v-on:eventName="handler", where eventName is the event like click and handler is the method or inline code to run.
You can also use the shorthand @eventName="handler" for cleaner code.
- v-on: directive to bind event listeners
- eventName: the event to listen for (e.g., click, input)
- handler: JavaScript method or inline expression to execute
html
<button v-on:click="sayHello">Click me</button> <!-- Shorthand --> <button @click="sayHello">Click me</button>
Example
This example shows a button that changes a message when clicked using v-on:click. It demonstrates how to bind a method to an event and update the component's data reactively.
vue
<template>
<div>
<p>{{ message }}</p>
<button v-on:click="updateMessage">Click me</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('Hello! Click the button.')
function updateMessage() {
message.value = 'You clicked the button!'
}
</script>Output
Hello! Click the button.
[Button labeled 'Click me']
(After clicking button)
You clicked the button!
Common Pitfalls
Common mistakes when using v-on include:
- Forgetting to use quotes around the handler expression.
- Trying to call methods without parentheses when needed.
- Using inline JavaScript that is too complex or not reactive.
- Not binding
thisproperly in methods (less common withscript setup).
Always use methods or simple expressions inside v-on and prefer the shorthand @ for cleaner code.
html
Wrong:
<button v-on:click=sayHello>Click me</button>
Right:
<button v-on:click="sayHello">Click me</button>Quick Reference
| Usage | Description | Example |
|---|---|---|
| Basic event binding | Listen to an event and call a method | |
| Shorthand | Shorter syntax for v-on | |
| Inline statement | Run inline JavaScript | |
| Event modifiers | Modify event behavior (e.g., prevent default) | |
| Multiple events | Listen to multiple events separately |
Key Takeaways
Use
v-on:eventName="handler" or shorthand @eventName="handler" to listen to events in Vue.Bind methods or simple expressions to handle user interactions like clicks or inputs.
Always wrap handler expressions in quotes to avoid syntax errors.
Use event modifiers like .prevent or .stop to control event behavior easily.
Keep event handlers simple and reactive for best performance and clarity.