Event Handling in Vue.js with Example
Today we’re going to learn how to handle event in Vue.js. Vue jas v-on
directive to listen to DOM events and run some JavaScript when they’re triggered.
Listening to Events
Let’s see an example of click event:
<template>
<div id="app">
<button v-on:click="counter += 1">Add 1</button>
<p>The button above has been clicked {{ counter }} times.</p>
</div>
</template>
<script>
export default {
data: function () {
return {
counter: 0
};
}
};
</script>
To trigger button click we’ve used click
modifier attach to v-on
directive.
To handle click event, there is a short syntax. This is the syntax:
<button @click="counter += 1">Add 1</button>
Pass Arguments
The event handler also accept arguments. Here’s an example:
<template>
<div id="app">
<button @click="greet('Obydul')">Say Hello</button>
</div>
</template>
<script>
export default {
methods: {
greet: function (value) {
console.log("Hello " + value);
}
}
};
</script>
Pass Event Object & Arguments
We’re able to pass arguments with event object too. Let’s see an example:
<template>
<div id="app">
<button v-on:click="warning('Form cannot be submitted yet.', $event)">
Submit
</button>
</div>
</template>
<script>
export default {
methods: {
warning: function (message, event) {
// now we have access to the native event
if (event) {
event.preventDefault()
}
alert(message)
}
}
};
</script>
I hope you understand the event. You’ll find more event examples on Vue.js documentation.

Md Obydullah
https://shouts.dev/obydul
Comments
No comments yet…