Event Handling in Vue.js with Example

Published on December 24, 2019 1 min read

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.

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

Leave a Reply

Your email address will not be published. Required fields are marked *