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
                }
            })
        });
    }

Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

2 thoughts on “Vue.js: Adding Keyboard Shortcuts to Components

  1. Very important : do not forget to remove the listener when the component is destroyed !
    Note that you will need to define the event callback in a named function to be properly able to target the listener to be removed (the methods section of the component is a good place to define it.)

    “`
    beforeDestroy: function () {
    window.removeEventListener(‘keyup’, this.handleKeyup)
    }
    “`

    Like

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