Categories
JavaScript Vue

Adding Keyboard Shortcut Handling to a Vue App with vue-shortkey

Spread the love

We can use the vue-shortkey package to add shortcut key handling to our Vue app.

To use it, we first install it by running:

npm i vue-shortkey

Then we can use it by writing:

<template>
  <div id="app">
    <button v-shortkey="['ctrl', 'alt', 'o']" @shortkey="theAction()">Open</button>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    theAction() {
      alert("hello");
    }
  }
};
</script>

We have a button that responds to the keyboard shortcut Ctrl+Alt+O.

When we press it, theAction will be called because we passed it into the shortkey event handler.

Then we should see the ‘hello’ alert displayed when we pressed the key combination.

We can also handle multiple key combinations with one handler.

For instance, we can write:

<template>
  <div id="app">
    <button v-shortkey="{up: ['arrowup'], down: ['arrowdown']}" @shortkey="theAction">arrow</button>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    theAction(event) {
      switch (event.srcKey) {
        case "up":
          alert("up");
          break;
        case "down":
          alert("down");
          break;
        default:
          break;
      }
    }
  }
};
</script>

We have the v-shortkey directive with an object with the up and down keys.

We have an array with the values as the values of the objecy.

Then in theAction, we take an event parameter which has the key we pressed.

We then have the switch statement and then we have alerts displayed according to the key pressed.

It can also be used on a component. However, we have to add the native modifier to catch the event.

For instance, we can write:

<template>
  <div id="app">
    <HelloWorld v-shortkey="['ctrl', 'alt', 'o']" @shortkey.native="theAction"/>
  </div>
</template>

<script>
import HelloWorld from "@/components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld
  },
  methods: {
    theAction() {
      alert("hello");
    }
  }
};
</script>

We added the v-shortkey directive to the HelloWorld component, and we used the native modifier on @shortkey so that the handler is run.

The full list of keys are at https://www.npmjs.com/package/vue-shortkey

vue-shortkey is a simple package that lets us add shortcut key handling capability to a Vue app that’s easier to use than the Vue way.

Leave a Reply

Your email address will not be published. Required fields are marked *