Vue Global Events

3.0.1 · active · verified Sun Apr 19

Vue Global Events is a lightweight library for Vue 3 that enables developers to register global keyboard and mouse events directly within Vue templates using familiar Vue event modifiers. It abstracts away the complexities of `addEventListener` and `removeEventListener` on `document` or `window`, automatically handling event lifecycle management in sync with component unmounting. The current stable version is 3.0.1, specifically designed for Vue 3. It differs from manual global event handling by leveraging Vue's declarative syntax and reactivity system, allowing events to be conditionally enabled/disabled with `v-if` and ensuring proper cleanup, including support for Server-Side Rendering (SSR). While there isn't a strict release cadence, updates are typically made to align with new Vue versions or to introduce minor enhancements and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install, register, and use the `GlobalEvents` component to listen for global keyboard shortcuts like `Ctrl+Space` and `Alt+S` within a Vue 3 application. It also shows conditional event listening with `v-if` and includes a basic input field to illustrate event filtering caveats.

import { createApp, ref } from 'vue';
import { GlobalEvents } from 'vue-global-events';

const App = {
  components: { GlobalEvents },
  setup() {
    const message = ref('Press Ctrl+Space to toggle, or Alt+S for a message.');
    const showGlobalEvents = ref(true);

    const toggleEvents = () => {
      showGlobalEvents.value = !showGlobalEvents.value;
      message.value = `Global events are now ${showGlobalEvents.value ? 'enabled' : 'disabled'}.`;
    };

    const showAltSMessage = () => {
      alert('Alt+S was pressed globally!');
      message.value = 'Alt+S was pressed!';
    };

    return {
      message,
      showGlobalEvents,
      toggleEvents,
      showAltSMessage,
    };
  },
  template: `
    <div>
      <h1>Vue Global Events Demo</h1>
      <p>{{ message }}</p>
      <button @click="toggleEvents">Toggle Global Events (Current: {{ showGlobalEvents ? 'ON' : 'OFF' }})</button>
      
      <GlobalEvents
        v-if="showGlobalEvents"
        @keyup.ctrl.space.prevent="toggleEvents"
        @keyup.alt.s="showAltSMessage"
        @keydown.prevent.page-down="() => message = 'Page Down was pressed!'"
      />
      
      <div style="margin-top: 20px;">
        <input type="text" placeholder="Type here to avoid triggering events" />
      </div>
    </div>
  `
};

createApp(App).mount('#app');

view raw JSON →