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.
Let me first demonstrate how to use it. You can define your shortcuts in a setup function like this:
<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:
_ 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.You can grab the source code from GitHub
If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :
