Table of contents [Show]
- Introduction to Vue.js Events
- Getting Started: The v-on Directive
- Basic Event Handling
- Accessing Event Object
- Event Modifiers in Vue.js
- Keyboard Event Handling
- Custom Events and Component Communication
- Advanced Event Handling Techniques
- Practical Example: Todo List with Events
- Best Practices for Event Handling in Vue.js
- Conclusion
Introduction to Vue.js Events
Vue.js is one of the most popular JavaScript frameworks for building interactive web applications. A major part of interactivity comes from handling user actions—like clicks, keyboard input, or form submissions. These actions are captured as events.
Vue.js simplifies event handling through its directive system, especially with v-on. This directive allows you to attach event listeners directly to elements in your template, making your code cleaner and easier to maintain.
In this article, we’ll explore Vue.js event handling comprehensively—from the basics of the v-on directive to advanced event modifiers and custom event communication between components.
Getting Started: The v-on Directive
What is v-on?
The v-on directive in Vue.js is used to listen for DOM events and run JavaScript when they’re triggered. It’s a fundamental directive in Vue that connects user interaction with your application logic.
Syntax:
<button v-on:click="methodName">Click Me</button>There’s also a shorthand for v-on, which is @. So the above code can also be written as:
<button @click="methodName">Click Me</button>Basic Event Handling
Handling a Click Event
Let’s start with a simple Vue instance where a button click triggers a message change.
<div id="app">
<p>{{ message }}</p>
<button @click="changeMessage">Click Me</button>
</div>
<script>
const app = Vue.createApp({
data() {
return {
message: "Hello Vue.js!"
}
},
methods: {
changeMessage() {
this.message = "Button was clicked!";
}
}
});
app.mount('#app');
</script>In this example, when the button is clicked, the changeMessage method updates the message property, and the UI automatically re-renders.
Passing Arguments to Methods
You can also pass arguments to methods through v-on. This is useful when the event handler needs context-specific values.
<div id="app">
<button @click="sayHello('John')">Say Hello</button>
</div>
<script>
const app = Vue.createApp({
methods: {
sayHello(name) {
alert("Hello, " + name + "!");
}
}
});
app.mount('#app');
</script>Accessing Event Object
Sometimes, you need access to the raw event object—for example, to determine which key was pressed or which mouse button was clicked. Vue lets you access the event object by passing $event.
<div id="app">
<input type="text" @keyup="showKey($event)" placeholder="Type something">
</div>
<script>
const app = Vue.createApp({
methods: {
showKey(event) {
alert("You pressed: " + event.key);
}
}
});
app.mount('#app');
</script>Event Modifiers in Vue.js
Vue provides event modifiers that simplify handling common event behaviors without writing extra JavaScript code. These modifiers are appended to event listeners using a dot (.)
Common Event Modifiers
Here’s a table of commonly used event modifiers:
| Modifier | Description | Example |
|---|---|---|
| .stop | Stops event propagation. | <button @click.stop="doThis">Click</button> |
| .prevent | Prevents default event behavior. | <form @submit.prevent="onSubmit"></form> |
| .capture | Attaches event in capture mode. | <div @click.capture="doThis"></div> |
| .once | Triggers the event handler only once. | <button @click.once="doThis">Click once</button> |
| .self | Triggers only if the event happened on the element itself. | <div @click.self="doThis"></div> |
Example: Preventing Default Form Submission
<form @submit.prevent="handleSubmit">
<input type="text" placeholder="Enter text">
<button type="submit">Submit</button>
</form>
<script>
const app = Vue.createApp({
methods: {
handleSubmit() {
alert("Form submitted via Vue.js, without page reload!");
}
}
});
app.mount('#app');
</script>Keyboard Event Handling
Vue offers key modifiers for handling keyboard events more intuitively. Instead of checking event.key, you can use key aliases directly.
<input @keyup.enter="submitInput" placeholder="Press Enter">
<script>
const app = Vue.createApp({
methods: {
submitInput() {
alert("Enter key pressed!");
}
}
});
app.mount('#app');
</script>Vue supports many key modifiers such as .enter, .tab, .delete, .esc, .space, .up, .down, .left, and .right.
Custom Events and Component Communication
In larger Vue applications, you often need to pass events between parent and child components. Vue uses a system of custom events for this.
Emitting Events from Child to Parent
<!-- ChildComponent.vue -->
<template>
<button @click="$emit('childClicked', 'Hello Parent!')">
Notify Parent
</button>
</template>
<script>
export default {
name: "ChildComponent"
}
</script><!-- ParentComponent.vue -->
<template>
<div>
<ChildComponent @childClicked="handleChildEvent" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
methods: {
handleChildEvent(message) {
alert("Message from child: " + message);
}
}
}
</script>Here, the child emits an event named childClicked, and the parent listens for it using @childClicked.
Advanced Event Handling Techniques
Event Handling with Inline JavaScript
Instead of binding to methods, you can run inline JavaScript expressions directly in v-on.
<button @click="count++">Increase Count</button>Multiple Event Handlers
You can assign multiple handlers to a single event by using methods inside your event handler.
<button @click="methodOne(); methodTwo()">Click Me</button>Practical Example: Todo List with Events
Let’s bring everything together in a simple Todo app where event handling plays a crucial role.
<div id="app">
<h2>Todo List</h2>
<input v-model="newTask" @keyup.enter="addTask" placeholder="Add a task">
<ul>
<li v-for="(task, index) in tasks" :key="index">
{{ task }}
<button @click="removeTask(index)">Remove</button>
</li>
</ul>
</div>
<script>
const app = Vue.createApp({
data() {
return {
newTask: "",
tasks: []
}
},
methods: {
addTask() {
if(this.newTask.trim() !== "") {
this.tasks.push(this.newTask);
this.newTask = "";
}
},
removeTask(index) {
this.tasks.splice(index, 1);
}
}
});
app.mount('#app');
</script>Here we use:
@keyup.enter→ Adds a new task when Enter is pressed.@click→ Removes a task when the remove button is clicked.
Best Practices for Event Handling in Vue.js
- Prefer
methodsover inline JavaScript for readability. - Use event modifiers to keep your code clean.
- Emit descriptive event names in components for clarity.
- Use
$eventonly when necessary; avoid overusing raw event objects. - Keep your methods focused—one method should ideally handle one task.
Conclusion
Mastering event handling in Vue.js with v-on is essential for building interactive and dynamic applications. From basic click handlers to complex parent-child communication, Vue’s event system is designed to be intuitive and powerful.
We’ve covered a complete journey—basic event handling, event modifiers, keyboard events, custom events, and a real-world Todo app. With these concepts, you’re now ready to handle user interactions effectively in Vue.js projects.






