·
1 min read

Vue Tip: Composable to Define Keyboard Shortcuts

MH

Michael Hoffmann

@mokkapps

Vue Tip: Composable to Define Keyboard Shortcuts Image

I want to show you a handy Vue composable that allows you to define keyboard shortcuts in your app. I discovered it in Nuxt UI, and it's called defineShortcuts.

How to Use It

Let me first demonstrate how to use it. You can define your shortcuts in a setup function like this:

App.vue
<script setup lang="ts">
const isActive = ref(false)

defineShortcuts({
  meta_k: {
    handler: () => {
      isActive.value = !isActive.value
    }
  }
})
</script>

I don't want to repeat the documentation, but let me highlight a few things:

  • Shortcuts can be combined with the _ character. For example, meta_k is the meta key (Command key on MacOS, Control on other OS) key and the k key.
  • usingInput is a flag that tells the composable to only trigger the shortcut when the user is not typing in an input field.
  • whenever is used to add constraints so that the shortcut is only triggered when the constraints are met. For example, you can use whenever: [isActive] to only trigger the shortcut when isActive is true.

Source Code

You can grab the source code from GitHub

If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :

I will never share any of your personal data. You can unsubscribe at any time.