Use o composable defineShortcuts, importado automaticamente, para definir atalhos de teclado.
<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.defineShortcuts(config: ShortcutsConfig, options?: ShortcutsOptions): void
Defina atalhos de teclado para a sua aplicação.
800.false (default): Uses e.key for character-based matching (Layout specific)true: Uses e.code for physical key matching (Layout agnostic)Os atalhos são definidos usando o seguinte formato:
'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 keysCada atalho pode ser definido como uma função ou um objeto com as seguintes propriedades:
interface ShortcutConfig { handler: () => void; usingInput?: boolean | string }
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>
A opção usingInput permite especificar que um atalho só deve ser disparado quando um input específico estiver em foco.
<template>
<NInput 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>
Use o utilitário extractShortcuts para definir atalhos automaticamente a partir de itens de menu.