Vue v-on Directive
🎯 Vue v-on Directive
What is Vue v-on Directive?
v-on attaches an event listener to an HTML element.
✔ When the button is clicked, sayHello() runs.
Basic Syntax
✔ Shorthand (Most Used)
Example:
Example 1: Click Event
Example 2: Calling a Method
Example 3: Passing Arguments
Example 4: Accessing Event Object ($event)
Event Modifiers
Vue provides modifiers to simplify common event tasks.
| Modifier | Purpose |
|---|---|
.prevent |
Prevent default behavior |
.stop |
Stop event propagation |
.once |
Run event only once |
.self |
Trigger only on element itself |
Example
Keyboard Events
Common Key Modifiers
-
.enter -
.tab -
.esc -
.space -
.up,.down
Mouse Event Modifiers
Multiple Events on One Element
v-on with Components (Custom Events)
📌 Used for child → parent communication.
Commonly Used v-on Events
-
@click -
@submit -
@input -
@change -
@keyup -
@keydown -
@mouseover -
@mouseleave
Best Practices ✅
✔ Use shorthand @
✔ Keep logic inside methods
✔ Use modifiers instead of event.preventDefault()
✔ Name methods clearly
Summary Table
| Task | Syntax |
|---|---|
| Click | @click="method" |
| Submit | @submit.prevent="method" |
| Keyboard | @keyup.enter="method" |
| One-time | @click.once="method" |
| Custom event | @eventName="method" |
Conclusion
The v-on directive is the backbone of interactivity in Vue.
Mastering v-on is essential before moving to forms, components, and advanced UI logic.
