Vue Tip: Composable to Define Keyboard Shortcuts
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:
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 thek
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 usewhenever: [isActive]
to only trigger the shortcut whenisActive
istrue
.
Source Code
You can grab the source code from GitHub
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Use a Head Manager
Unhead is a framework-agnostic document head manager that can be used to manage page metadata like the title in your Vue application.
Vue Tip: Document Your Component Props Using JSDoc
You can use JSDoc to document your component props so that they show up when you hover over the component in your IDE.