DEV Community

Discussion on: Vue Event Handler Arguments

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.