Home

Awesome

vue-global-events Build Status npm package

Add shortcuts by listening to events on the document, anywhere

This is the version for Vue 3, if you are looking for the Vue 2 version, take a look at the v1 branch

Sponsors

Bronze

<p align="center"> <a href="https://www.vuemastery.com/" target="_blank"> <img src="https://cdn.discordapp.com/attachments/258614093362102272/557267759130607630/Vue-Mastery-Big.png" alt="Vue Mastery logo" width="180px"> </a> <a href="https://vuejobs.com/" target="_blank"> <img src="https://cdn.discordapp.com/attachments/560524372897562636/636900598700179456/vuejobs-logo.png" alt="Vue Jobs logo" width="140px"> </a> </p>

Installation

yarn add vue-global-events
npm install vue-global-events

Demo

Idea

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 removing them either. You can toggle the events with a single v-if. Works with SSR too.

Usage

import { GlobalEvents } from 'vue-global-events'

// register globally
app.component('GlobalEvents', GlobalEvents)

// or locally
export default {
  components: { GlobalEvents },
  // rest of your component
}

After that you can register global events like this:

<GlobalEvents
  v-if="listenersConnected"
  @keyup.ctrl.tab="nextTab"
  @keyup.ctrl.shift.tab="previousTab"
  @keyup.space="pause"
  @contextmenu="openMenu"
/>

Props

target

Target element where addEventListener is called on. It's a String that refers to a global variable like document or window. This allows you to add events to the window instead of document.

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:

<GlobalEvents :target="target" :key="target" />

filter

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.

arguments

filter should return false to prevent the execution of a handler. For example, you can avoid the calls if the event is triggered by an <input>:

<GlobalEvents
  :filter="(event, handler, eventName) => event.target.tagName !== 'INPUT'"
  @keyup.prevent.space.exact="nextTab"
/>

In the example above event would be the native keyup Event Object, handler would be the method nextTab and eventName would be the string keyup.

Advice / Caveats

Development

Run tests in watch mode:

yarn jest --watch

Authors

Damian Dulisz @shentao

Eduardo San Martin Morote @posva

License

MIT

<div align="right"> <sub><em> This project was created using the <a href="https://github.com/shentao/vue-global-events-boilerplate" rel="nofollow">Vue Library boilerplate</a> by <a href="https://github.com/posva" rel="nofollow">posva</a> </em></sub> </div>