
Vue.js Event Handling – v-on, Methods & Event Modifiers
🎯 Introduction
In Vue.js, handling user interactions like clicks, typing, and form actions is done using the powerful v-on directive.
It allows you to listen to events and trigger functions (methods) when those events occur.
⚡ 1. v-on Directive (Event Binding)
The v-on directive is used to listen to DOM events like click, input, submit, etc.
✅ Example: Click Event
<button v-on:click="showMessage">Click Me</button>
👉 Short form:
<button @click="showMessage">Click Me</button>
✅ Example: Input Event
<input v-on:input="getInput">
🧠 2. Methods in Vue.js
Methods are functions defined inside the Vue instance that handle logic.
✅ Example:
<div id="app">
<button @click="increment">Click</button>
<p>Count: {{ count }}</p>
</div><script>
Vue.createApp({
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
}
}
}).mount('#app')
</script>
⚡ 3. Passing Parameters in Events
You can pass values to methods.
<button @click="sayHello('Himanshu')">Click</button>
methods: {
sayHello(name) {
alert("Hello " + name)
}
}
🔥 4. Event Modifiers (Important)
Event modifiers are special suffixes that make event handling easier.
✅ Common Modifiers
🔹 .prevent
Prevents default behavior (like form submit refresh)
<form @submit.prevent="submitForm">
🔹 .stop
Stops event propagation (bubbling)
<button @click.stop="doSomething">
🔹 .once
Runs event only once
<button @click.once="handleClick">
🔹 .capture
Captures event during capture phase
<div @click.capture="handleClick">
🔹 .self
Triggers only if event target is the element itself
<div @click.self="handleClick">
⚡ 5. Key Modifiers (Keyboard Events)
Used for keyboard inputs.
<input @keyup.enter="submit">
👉 Other keys:
.tab.delete.esc.space
🔥 Real Example (All Concepts Together)
<div id="app">
<input v-model="name" @keyup.enter="greet">
<button @click="greet">Say Hello</button>
</div><script>
Vue.createApp({
data() {
return {
name: ""
}
},
methods: {
greet() {
alert("Hello " + this.name)
}
}
}).mount('#app')
</script>
🧩 Quick Summary
v-on→ listen to events@click→ shorthand of v-onmethods→ handle logicmodifiers→ control event behavior
🏁 Conclusion
Vue.js event handling is simple yet powerful. Using v-on, methods, and modifiers, you can build highly interactive and responsive applications with minimal code.
