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.
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)