Vue Events

Vue Events (v-on)
It uses the v-on directive to listen to DOM events.
What are Vue Events?
Events allow you to execute JavaScript methods when a user interacts with the UI.
Examples:
Button click
Key press
Mouse hover
Form submit
Basic Syntax
Shorthand (Recommended)
Example 1: Click Event
2: Inline Event Handler
3: Passing Parameters
4: Event Object ($event)
Event Modifiers
Event modifiers change default behavior easily.
| Modifier | Description |
|---|---|
.prevent | Prevent default action |
.stop | Stop event bubbling |
.once | Trigger only once |
.self | Trigger only on element itself |
Example
Keyboard Events
Vue provides key modifiers.
Common Keys
.enter.tab.esc.space.up,.down,.left,.right
Mouse Event Modifiers
Multiple Events
Events with Components
Child → Parent communication using custom events.
Commonly Used Events
@click@submit@change@input@keyup@keydown@mouseover@mouseleave
Best Practices
- Use methods instead of inline logic for complex code
- Use modifiers to keep code clean
- ✔ Name methods clearly (
handleSubmit,onClick)
Summary Table
| Task | Syntax |
|---|---|
| Click | @click="method" |
| Submit | @submit.prevent="method" |
| Keyboard | @keyup.enter="method" |
| Pass data | @click="method(value)" |
| Emit event | $emit('eventName') |
Conclusion
Events make your application interactive and dynamic.
Mastering v-on, event modifiers, and custom events is crucial before moving to forms, components, and state management.
