This is a Vue.js mixin (or rather, a mixin factory) for simple keyboard shortcuts.
Features:
- Tiny (<0.5 KB minified & gzipped)
- Super easy to use
- Proper restrictions (does not trigger when modifier keys don't match exactly or when an element has focus)
Note that this mixin targets modern browsers. If you need legacy browser support, you need to use a transpiler like Babel with the according polyfills.
No modifiers, just a single key press:
import shortcut from './shortcut.mjs'
new Vue({
mixins: [
shortcut('ArrowLeft', function() {
// Arrow left key was pressed
}),
shortcut('ArrowRight', function() {
// Arrow right key was pressed
})
]
})
Note: Key names are case insensitive. That means that
shortcut('A', ...)
will also match key presses ofa
(without shift key pressed) and vice versa.
The modifiers you know and love from the KeyboardEvent
are available: Control, Alt, Shift and Meta.
You can import them from the module and pass a bitmask of them to the shorcut
function as an optional second argument.
import shortcut, { CTRL, ALT } from './shortcut.mjs'
new Vue({
mixins: [
shortcut('a', CTRL | ALT, function() {
// Control + Alt + A was pressed
})
]
})
There are some additional modifiers available for comfort: CMD
and WIN
are both aliases to the META
modifier, but they only apply if the user is on the according OS.
In addition, there is PRIMARY
. It represents the primary modifier key of the user's operating system and aliases either CMD
(on macOS) or CTRL
(on other operating systems).
import shortcut, { PRIMARY } from './shortcut.mjs'
new Vue({
mixins: [
shortcut('s', PRIMARY, function() {
// Matches Command + S on macOS and Control + S on other systems
})
]
})
If you want to perform actions on the triggered KeyboardEvent
, you can access the event as the first parameter to the shortcut callback:
import shortcut, { PRIMARY } from './shortcut.mjs'
new Vue({
mixins: [
shortcut('s', PRIMARY, function(event) {
// Prevent the browser from saving the page
event.preventDefault()
// Perform custom save logic instead...
})
]
})
We are not restricted to passing key names as the first argument to the shortcut
function. A callback function which determines whether a pressed key matches your requirements will be accepted as well:
import shortcut from './shortcut.mjs'
new Vue({
mixins: [
shortcut(event => /^[0-9]$/.test(event.key), function() {
// A number key was pressed
})
]
})
Thanks for sharing, but It doesn't work for me I don't know why. It's instantiating the event listener but it never call the callback 😢 . I think I'm doing something wrong...