Use the auto-imported defineShortcuts composable to define keyboard shortcuts.
<script setup lang="ts">
const open = ref(false)
defineShortcuts({
meta_k: () => {
open.value = !open.value
}
})
</script>
meta to ctrl.useEventListener to handle keydown events.KeyboardEvent.key API documentation. Note that the key should be written in lowercase.Learn how to display shortcuts in components in the Kbd component documentation.
defineShortcuts(config: ShortcutsConfig, options?: ShortcutsOptions): void
Define keyboard shortcuts for your application.
An object where keys are shortcut definitions and values are either handler functions or shortcut configuration objects.
Optional configuration for the shortcuts behavior.
The delay between key presses to consider the shortcut as chained. Default is 250.
Shortcuts are defined using the following format:
'a', 'b', '1', '?', etc._ to separate keys, e.g., 'meta_k', 'ctrl_shift_f'- to define a sequence, e.g., 'g-d'meta: Represents ⌘ Command on macOS and Ctrl on other platformsctrl: Represents Ctrl on all platformsshift: Used for alphabetic keys when Shift is requiredescape: Triggers on Esc keyenter: Triggers on Enter keyarrowleft, arrowright, arrowup, arrowdown: Trigger on respective arrow keysEach shortcut can be defined as a function or an object with the following properties:
interface ShortcutConfig { handler: () => void; usingInput?: boolean | string }
Function to be executed when the shortcut is triggered.
Controls when the shortcut should trigger based on input focus:
false (default): Shortcut only triggers when no input is focusedtrue: Shortcut triggers even when any input is focusedstring: Shortcut only triggers when the specified input (by name) is focused<script setup lang="ts">
defineShortcuts({
'?': () => openHelpModal(),
'meta_k': () => openCommandPalette(),
'g-d': () => navigateToDashboard()
})
</script>
The usingInput option allows you to specify that a shortcut should only trigger when a specific input is focused.
<template>
<UInput v-model="query" name="queryInput" />
</template>
<script setup lang="ts">
const query = ref('')
defineShortcuts({
enter: {
usingInput: 'queryInput',
handler: () => performSearch()
},
escape: {
usingInput: true,
handler: () => clearSearch()
}
})
</script>
The extractShortcuts utility can be used to automatically define shortcuts from menu items:
<script setup lang="ts">
const items = [{
label: 'Save',
icon: 'i-lucide-file-down',
kbds: ['meta', 'S'],
onSelect() {
save()
}
}, {
label: 'Copy',
icon: 'i-lucide-copy',
kbds: ['meta', 'C'],
onSelect() {
copy()
}
}]
defineShortcuts(extractShortcuts(items))
</script>