Vue 3 keyboard shortcut library.
Also usable in Vue 2 with to VueDemi. For Vue 2 the @vue/composition-api is required.
Install the package as a dependency in your project:
npm install --save @simolation/vue-hotkey
# or with yarn
yarn add @simolation/vue-hotkeyThis library supports a comprehensive set of keyboard keys and combinations:
primary- Command key on macOS, Control key on other platformssecondary- Control key on macOS, Alt key on other platforms
meta- Meta/Windows/Command keyctrl- Control keyalt- Alt keyshift- Shift keyaltgraph- AltGraph key
esc- Escape keyenter- Enter/Return keytab- Tab keyspace- Space bararrowup,arrowdown,arrowleft,arrowright- Arrow keyspageup,pagedown- Page navigationhome,end- Home and End keys
del- Delete keybackspace- Backspace keyinsert- Insert key
numlock,capslock,scrolllock- Toggle keys
f1throughf12- Function keys
- All letters (a-z), numbers (0-9), and symbols are supported
- Keys are case-insensitive and automatically normalized
The library supports alternative names for common keys:
Basic Keys:
deleteordel- Delete keyescapeoresc- Escape keyreturnorenter- Enter/Return keyspacebarorspace- Space barinsorinsert- Insert key
Arrow Keys:
up/down/left/rightorarrowup/arrowdown/arrowleft/arrowright
Modifier Keys:
controlorctrl- Control keycommand/cmdormeta- Meta/Command keyoption/optoralt- Alt/Option keywindows/win/superormeta- Windows/Super key
Page Navigation:
pgup/pgdn/pgdown/pagednorpageup/pagedown
Lock Keys:
capsorcapslock- Caps Lock keynumornumlock- Num Lock keyscrollorscrolllock- Scroll Lock key
Other Keys:
context/menuorcontextmenu- Context Menu keyfunction/fn- Function key
Combine keys using arrays: ['ctrl', 's'], ['primary', 'shift', 'n'], ['alt', 'f4'], ['delete']
This package can be used as a Vue component or as a hook.
The idea behind the component is to wrap, for example, a button with the Hotkey component to have a strong connection between the element, which would trigger the action without the hotkey. There will be no hotkey code scattered throughout your application.
Import the Hotkey component in your Vue file:
import { Hotkey } from "@simolation/vue-hotkey";Register it as a component:
export default defineComponent({
// ...
components: {
Hotkey,
},
// ...
setup() {
return {
// This is the action that will be triggered when the hotkey is activated
action: () => {
console.log("Ctrl + s has been pressed!");
},
};
},
});Use it in your template:
<template>
<Hotkey :keys="['ctrl', 's']" @hotkey="action">
<!-- any content -->
</Hotkey>
</template>It is also possible to click or focus the slot element:
<Hotkey :keys="['ctrl', 's']" v-slot="{ clickRef }">
<button :ref="clickRef" @click="action">Hotkey or click</button>
</Hotkey><Hotkey :keys="['ctrl', 's']" v-slot="{ focusRef }">
<input :ref="focusRef" type="text" />
</Hotkey>By default, the hotkey prevents the default action and is not propagated to the parent.
With :propagate="true" the event will be passed to the parent listeners as well and trigger the default action.
<template>
<Hotkey :keys="['ctrl', 's']" propagate @hotkey="action">
<!-- any content -->
</Hotkey>
</template>When the hotkey should not be usable, it can easily be disabled by setting disabled.
<template>
<Hotkey :keys="['ctrl', 's']" disabled @hotkey="action">
<!-- any content -->
</Hotkey>
</template>By default, input and textarea fields are excluded. This can be overwritten and changed by specifying the :excluded-elements="['radio', 'div']" option.
It will prevent the hotkey when the currently focused HTML element is of the specified type.
<template>
<Hotkey
:keys="['ctrl', 's']"
:excluded-elements="['radio', 'div']"
@hotkey="action"
>
<!-- any content -->
</Hotkey>
</template>Control the order in which hotkeys are executed when multiple components register the same hotkey. Higher priority numbers take precedence. Useful for modals, popups, and overlays.
<template>
<!-- Base application ESC handler (low priority) -->
<Hotkey :keys="['esc']" :priority="0" @hotkey="closeApp">
<!-- app content -->
</Hotkey>
<!-- Modal ESC handler (higher priority) -->
<Hotkey :keys="['esc']" :priority="100" @hotkey="closeModal" v-if="showModal">
<!-- modal content -->
</Hotkey>
<!-- Popup ESC handler (highest priority) -->
<Hotkey :keys="['esc']" :priority="200" @hotkey="closePopup" v-if="showPopup">
<!-- popup content -->
</Hotkey>
</template>When multiple hotkeys with the same key combination are registered:
- Higher priority executes first - Priority 200 runs before priority 100
- Same priority uses registration order - Newer registrations take precedence
- Only one handler executes - Unless
propagateis enabled
Only call a function when the hotkey is pressed. Can be used for special on-click actions based on a hotkey.
<template>
<Hotkey :keys="['alt']" v-slot="{ keyCheck }">
<button @click="keyCheck(onClick)">Click</button>
</Hotkey>
</template>When there is no specific element tied to the hotkey, it can be used as a hook with useHotkey():
import { useHotkey } from "@simolation/vue-hotkey";
useHotkey({
keys: ["ctrl" + "s"],
handler: () => {
console.log("Ctrl + s has been pressed!");
},
// optional:
propagate: ref(false),
enabled: ref(true),
priority: 100, // Higher numbers = higher priority
});The hook returns three functions to enable, disable or destroy the hotkey.
The hotkey does not need to be destroyed onUnmount, as the hook already takes care of that.
const { enable, disable, destroy } = useHotkey({ ... })
// Enable or disable the hotkey
enable()
// or
disable()
// Completely destroy the hotkey. It can not be enabled() again.
destroy()The excluded elements can be specified with the hook as well. The default is again input and textarea.
useHotkey(
{
keys: ["ctrl" + "s"],
handler: () => {
console.log("Ctrl + s has been pressed!");
},
},
["radio", "div"]
);The function provided as a parameter to the keyCheckFn will only be called when the hotkey is pressed when calling the returned function
const { keyCheckFn } = useHotkey({ ... });
const doSomething = keyCheckFn((name: string, count: number) => {
// do anything while the hotkey is pressed when doSomething is called
})
doSomething("myProps", 123);Use priority to control the execution order when multiple hooks register the same hotkey:
// Base level hotkey (default priority 0)
useHotkey({
keys: ["esc"],
handler: () => console.log("Base ESC handler"),
});
// Modal hotkey (higher priority)
useHotkey({
keys: ["esc"],
handler: () => console.log("Modal ESC handler"),
priority: 100,
});
// Only the modal handler will execute (highest priority)
// Unless propagate: ref(true) is set