JAVASCRIPT
Custom Click-Outside Directive
Implement a reusable custom Vue 3 directive `v-click-outside` to detect clicks that occur outside a specific DOM element, useful for closing modals, dropdowns, or tooltips.
// directives/vClickOutside.js
export const vClickOutside = {
beforeMount(el, binding) {
el.clickOutsideEvent = function (event) {
// Check if the clicked element is outside of the bound element
// and not the bound element itself
if (!(el === event.target || el.contains(event.target))) {
// Call the provided handler function
binding.value(event);
}
};
document.addEventListener('click', el.clickOutsideEvent);
},
unmounted(el) {
document.removeEventListener('click', el.clickOutsideEvent);
},
};
// main.js (or wherever you initialize Vue app)
import { createApp } from 'vue';
import App from './App.vue';
import { vClickOutside } from './directives/vClickOutside';
const app = createApp(App);
app.directive('click-outside', vClickOutside);
app.mount('#app');
// App.vue (Example usage)
<script setup>
import { ref } from 'vue';
const showDropdown = ref(false);
const closeDropdown = () => {
console.log('Clicked outside dropdown!');
showDropdown.value = false;
};
</script>
<template>
<div>
<h1>Click Outside Directive Example</h1>
<button @click="showDropdown = !showDropdown">Toggle Dropdown</button>
<div
v-if="showDropdown"
v-click-outside="closeDropdown"
style="border: 1px solid #ccc; padding: 20px; margin-top: 10px; background: white; position: absolute;"
>
<p>This is a dropdown content.</p>
<p>Click anywhere outside to close it.</p>
<button @click="showDropdown = false">Close (internal)</button>
</div>
</div>
</template>
How it works: This snippet defines a custom Vue 3 directive `v-click-outside`. The `beforeMount` hook attaches a global click event listener to the document. Inside the listener, it checks if the click occurred outside the element to which the directive is bound. If so, it executes the handler function provided as the directive's value (`binding.value`). The `unmounted` hook ensures the event listener is properly removed to prevent memory leaks. The example usage in `App.vue` demonstrates how to apply `v-click-outside` to a dropdown to automatically close it when a user clicks anywhere outside its boundaries.