Jun 09, 2019

How to Handle Keyboard Shortcuts in Vue (without plugins)?

Remember the left-pad fiasco and the ensuing criticism that the node community is lazy to an extent that it’ll avoid writing even a trivial piece of code? There’s a form of it in the frontend world, where libraries are the first choice even when the same thing could be achieved in a few lines of code.

I wanted to add keyboard shortcuts to my VueJs app and the first result I get on Google talks about the pluign vue-shortkey. Of course, it makes things dead simple, but would you prefer to add a whole library for a couple of keyboard shortcuts? The size of the plugin might be tiny but it adds to the page weight and adds an avoidable dependency to code. My preferance is to use the DOM API unless the library saves hours of effort or there are too many browser quirks to handle.

In this tutorial, I’ll be talking about how you can add keyboard shortcuts in your VueJS app without using any plugin.

Consider a barebones note taking app that creates a list of notes.

<!-- index.html -->
<div id="notes">
    <textarea v-model="currNote"></textarea>
    <div>
        <button @click="saveNote()">Save</button>
    </div>

    <h1>Notes</h1>
    <ul>
        <li v-for="note in notesList">{{ note }}</li>
    </ul>
</div>
// app.js
new Vue({
    el: "#notes",
    data: {
      currNote: "",
      notesList: []
    },
    methods: {
        saveNote () {
            this.notesList.push (this.currNote);
        }
    }
});

Let’s say you want to add a keyboard shortcut Cmd/Ctrl + S to save the note in the textarea. How would you do it? First, let’s see how would you listen for those shortcuts.

You can do it by listening to the key down event. The new “key” attribute is available in all major browsers, and allows you to check a keypress referencing its name (in contrast to the older API which needed key codes). To detect Cmd/Ctrl + S, our code would look something like this:

document.onkeydown = function(e) {
    if (e.key === "s" && (e.ctrlKey || e.metaKey)) {
        e.preventDefault(); // present "Save Page" from getting triggered.

        alert("The shortcut was pressed");
    }
};

To integrate this with your Vue app, you can add these listeners when the app/component gets mounted, and remove them when the app gets destoryed. So our app becomes:

new Vue({
    el: "#notes",
    data: {
      currNote: "",
      notesList: []
    },
    methods {
        saveNote() {
            this.notesList.push (this.currNote);
        }
    },
    mounted() {
        this._keyListener = function(e) {
            if (e.key === "s" && (e.ctrlKey || e.metaKey)) {
                e.preventDefault(); // present "Save Page" from getting triggered.

                this.saveNote();
            }
        };

        document.addEventListener('keydown', this._keyListener.bind(this));
    },
    beforeDestroy() {
        document.removeEventListener('keydown', this._keyListener);
    }
});

And that’s it. The lighter way to add keyboard shortcuts to your Vue app.


Follow Me!

I write about things that I find interesting. If you're modestly geeky, chances are you'll find them too.

Subscribe to this blog via RSS Feed.

Don't have an RSS reader? Use Blogtrottr to get an email notification when I publish a new post.