Vue ClickOutside Directive

1.1.0 · abandoned · verified Sun Apr 19

This package provides a simple Vue.js directive, `v-click-outside`, designed to detect clicks that occur outside of the element it is bound to. Primarily developed for Vue 2, the package (version 1.1.0) was last published over six years ago, indicating it is no longer actively maintained. Its straightforward implementation allows developers to easily create components like dropdowns or modals that close when a user clicks anywhere outside their boundaries. Due to its age, it does not support Vue 3's directive API changes or Composition API patterns. For modern Vue 3 projects, developers should consider updated alternatives like `@vueuse/core`'s `onClickOutside` composable or `v-click-outside` from other maintainers that have been updated for Vue 3.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and locally register the `v-click-outside` directive to create a toggleable popup that closes when clicking anywhere outside of it. This example is for Vue 2 applications.

<template>
  <div>
    <button v-click-outside="hide" @click="toggle">Toggle Popup</button>
    <div v-show="opened" class="popup-content">
      This is a popup item. Click outside to close.
    </div>
  </div>
</template>

<script>
import ClickOutside from 'vue-click-outside'

export default {
  data () {
    return {
      opened: false
    }
  },

  methods: {
    toggle () {
      this.opened = !this.opened
    },

    hide () {
      // Only close if it's currently open
      if (this.opened) {
        this.opened = false
      }
    }
  },

  mounted () {
    // Important: Prevent click outside event from being triggered by a click
    // on the element itself when using 'popupItem' for detection.
    // In this specific implementation, it uses $el to bind to the root element.
    this.popupItem = this.$el
  },

  // Don't forget to register the directive locally
  directives: {
    ClickOutside
  }
}
</script>

<style scoped>
.popup-content {
  border: 1px solid #ccc;
  padding: 20px;
  background-color: white;
  margin-top: 10px;
}
</style>

view raw JSON →