DEV Community

Cover image for Vue Event Handler Arguments

Vue Event Handler Arguments

Dan Vega on March 06, 2019

This article was originally posted at https://www.danvega.dev/blog/2019/03/04/vue-event-arguments A fundamental skill in learning JavaScript and...
Collapse
 
drozerah profile image
Drozerah • Edited

Hi Dan, thank you for your article, in addition we also can listen events from targets like Document or Window - or any object that implements the EventListener interface - when the Vue instance is created. The Vue created hook allows to add code which is run if the Vue instance is created as a step of the Vue Lifecycle...

For instance, here is a way for listening a window keydown event at the created step of the Vue instance.

var vm = new Vue({
    el: '#app',
    data: {
        eventKey: ''
    },
    created: function () {
        window.addEventListener('keydown', this.getKeyInfo)
    },
    methods: {
        getKeyInfo(event) {
            event.preventDefault()
            this.eventKey = event.key
        }
    }
})

We use an event listener callback function getKeyInfo(event) as a Vue method to return the key value of the key represented by the event into the Vue data object...

See that in action !

Collapse
 
therealdanvega profile image
Dan Vega

Thanks for the reply. You could also listen in the beforeDestroy hook and then remove the event listener. This is the point in which Vue will tear down any event listeners it has registered.

Collapse
 
zzzzbov profile image
Timothy

Please use <button> elements as these are not actually links, and tutorial code has a way of making its way into production by people who don't know better.

Collapse
 
paulwvnjohi profile image
Paul Wanjohi

"There is a shorthand for the v-on: directive which is to just use the colon... " I think you meant the @ symbol

Collapse
 
therealdanvega profile image
Dan Vega

oops, nice catch. Thanks Paul