Vue & Nuxt Tips
·
1 min read
·635 views
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_kis the meta key (Commandkey on MacOS,Controlon other OS) key and thekkey. usingInputis a flag that tells the composable to only trigger the shortcut when the user is not typing in an input field.wheneveris used to add constraints so that the shortcut is only triggered when the constraints are met. For example, you can usewhenever: [isActive]to only trigger the shortcut whenisActiveistrue.
Source Code
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 :

