Vue Click Outside Element Directive

3.1.2 · active · verified Wed Apr 22

Vue-Click-Outside-Element is a specialized Vue directive designed to detect clicks that occur outside the DOM element it is applied to, rather than outside a Vue component. This distinction is crucial for scenarios where event delegation needs to target a specific HTML element. The current stable version is 3.1.2, which offers improved TypeScript typings and better testing, particularly for Vue 3. The package has seen recent updates, including a transition to Vite for building (v3.1.0) and significant refactoring for Vue 3 compatibility (v3.0.0). It is maintained with a clear roadmap, including plans to potentially combine element and component click-outside functionalities in the future. It's a lightweight solution focused solely on element-level click detection, differentiating it from more generalized event handling libraries or those specifically for component-level interaction.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install and register the `v-click-outside-element` directive globally, then apply it to a button. Clicking anywhere outside the button will trigger the `closeButton` method, hiding the button. A secondary button allows you to bring the original button back into view.

import { createApp } from 'vue';
import vueClickOutsideElement from 'vue-click-outside-element';

// App.vue (within a single file component or separate)
const App = {
  template: `
    <div id="app">
      <button v-click-outside-element="closeButton" v-if="showButton" style="padding: 10px; background-color: lightblue;">Click outside me to hide</button>
      <p v-else>Button is hidden. Click anywhere to reset.</p>
      <button @click="showButton = true" v-if="!showButton" style="margin-top: 20px;">Show Button Again</button>
    </div>
  `,
  data() {
    return { showButton: true };
  },
  methods: {
    closeButton(event) {
      console.log('Clicked outside the button!', event.target);
      this.showButton = false;
    }
  }
};

const app = createApp(App);
app.use(vueClickOutsideElement);
app.mount('#app');

view raw JSON →