Vue.js: Adding Keyboard Shortcuts to Components

A simple method for adding keyboard shortcuts to your components is to do the following:

    1. Add the ‘mounted’ lifecycle event hook to your component
    2. Add an event listener to the ‘window’ object and have it listen for the ‘keyup’ event
    3. Check for the proper keyboard key code and system modifier key (command/control, option/alt, shift, etc.) combination
    4. Execute custom logic in response

Example: here the key combination ‘alt+n’ is being checked for

 mounted: function () {
        this.$nextTick(function () {
            window.addEventListener('keyup', event => {
                if(event.altKey && event.keyCode === 78){
                    //TODO: do/call something here
                }
            })
        });
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s