Vue 3 Click Away Directive

1.2.4 · active · verified Sun Apr 19

vue3-click-away is a Vue 3.x compatible directive designed to detect click events that occur outside of a specified element. It provides a simple mechanism for components to react when a user clicks anywhere on the document except on the element itself or its children. Currently at version 1.2.4, the package sees irregular but active maintenance, primarily addressing critical fixes such as recent server-side rendering (SSR) compatibility issues. Key differentiators include its explicit support for Vue 3's plugin system, direct directive registration, and a mixin option, offering flexibility in integration depending on the project's setup and preference. It ships with TypeScript types, facilitating its use in TypeScript-first Vue projects. Its primary goal is to abstract away the complexity of managing global click listeners for 'click away' scenarios.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the global registration of vue3-click-away as a Vue plugin and its basic usage within a component to detect clicks outside a specific element, incrementing a counter upon detection.

import { createApp } from 'vue';
import VueClickAway from 'vue3-click-away';

const App = {
  template: `
    <div style="padding: 20px; border: 1px solid #ccc;" v-click-away="onClickAway">
      Click inside me! ({{ clickCount }} clicks)
      <p>This box detects clicks outside itself.</p>
    </div>
    <button @click="resetCount">Reset Counter</button>
    <p>Click anywhere else on the page.</p>
  `,
  data() {
    return { clickCount: 0 };
  },
  methods: {
    onClickAway(event) {
      this.clickCount++;
      console.log('Clicked away!', event);
    },
    resetCount() {
      this.clickCount = 0;
    }
  }
};

const app = createApp(App);

app.use(VueClickAway); // Register the directive globally
app.mount('#app');

// To run this in a real HTML file, you would need a div with id="app":
// <div id="app"></div>

view raw JSON →