Add shortcuts by listening to events on the document, anywhere
npm install vue-global-events
Thanks to Vue’s event modifiers, handling events is extremely easy however, you’re limited to DOM element events.
We decided to change that, so now you can register global events (for example application shortcuts) just like you would listen to events on a component. No need to worry about unregistration either. You can toggle the events with a single
v-if. Works with SSR too.
// register globallyVue// or locallycomponents: GlobalEvents// rest of your component
After that you can register global events like this:
Function to prevent any event from being executed based on anything related to the event like the element that triggered it, the name, or the handler.
() => true
event: Native Event Object
handler: method passed to
eventName: event name with key modifiers
filter should return
false to prevent the execution of a handler:
Target element where
addEventListener is called on. It's a String that refers to a global variable like
window. This allows you to add events to the
window instead of
Warning: This prop is not reactive. It should be provided as a static value. If you need it to be reactive, add a
key attribute with the same value:
Advice / Caveats
.ctrland other modifiers as browsers may be using them as shortcuts.
- Do not use shortcuts that are used by the system or that the browser does not allow you to
.preventDefault(). The list includes
Cmd+W. You can find more information in this StackOverflow answer.
- Prefer using actual characters to keyCodes whenever possible:
@keydown.+for detecting the plus sign. This is important because symbols and numbers on the digit row will provide different keyCodes depending on the layout used.
- You can add custom keyCodes to
Vue.config.keyCodes. This is especially useful for numbers on the digit row: add
Vue.config.keyCodes.digit1 = 49so you can write
@keydown.1will trigger when
keyCode === 1.
- About using
keyupwith modifiers like
.shift: the keyup event is triggered when a key is released and that's also when the
event.ctrlKeyis checked, which if you just released, will be false. This is because
altare checked differently. If you want to trigger on the
keyupevent of a modifier, you need to use its keycode (check it here. For example, for the
ctrlkey, that would be:
@keyup.17. You can also use the advice above this one to provide it a name like ctrlkey.
Run tests in watch mode:
npm run dev
Build the library with:
npm run build
And then open the
Damian Dulisz @shentao
Eduardo San Martin Morote @posva