Exploring Custom Directives
\n\n
I'm focused on the user's need for custom directives in Vue 3. Currently, I'm defining the core concepts involved, specifically how Vue 3 directives are used, and their intended purpose in handling complex interactions. This helps me frame a solid example.
Structuring Directive Explanations
\n\n
I've outlined several real-world scenarios for custom directives, including click-outside, long-press, and intersection observers, which provides a range of complexity to demonstrate. I'm prioritizing clarity. I am now refining the explanations.
Formulating Code Examples
\n\n
I've decided to move away from tooltips and instead focus on an Intersection Observer directive. I'm now drafting the code for three directives: click-outside, long-press, and intersect, emphasizing clear logic. I'm sketching out the necessary lifecycle hooks for each directive and considering edge cases for better robustness. I'm making sure to comment everything clearly.
Choosing the Examples
\n\n
My current thinking is focused on the most effective examples, now. I've chosen click-outside and long-press as they're well-suited for illustrating directive implementation, but I'm debating the third example again, leaning towards v-intersect to demonstrate scroll interactions. This allows a good balance of interactivity and practical scenarios.
Defining Directive Implementations
\n\n
I'm now detailing the implementation specifics for each directive. I've completed the base click-outside code. The next task is coding up long-press. I'm using timers and event listeners, making sure to consider lifecycle hooks. I've started the skeleton for the Intersection Observer directive.
Custom directives in Vue 3 are best used when you need low-level access to the DOM for interactions that are difficult to manage with standard template syntax (like standard event listeners). Vue 3 changed the directive lifecycle hooks to better match component lifecycles (e.g., bind is now beforeMount, inserted is now mounted).
Here are implementations for three common complex interaction patterns: Click Outside, Long Press, and Intersection/Scroll Animation.
1. The "Click Outside" Directive
Used for closing modals, dropdowns, or context menus when the user clicks anywhere else on the screen.
directives/clickOutside.js
export const vClickOutside = {
mounted(el, binding) {
// Define the handler logic
el.clickOutsideEvent = (event) => {
// Check if the click target is the element itself or its children
if (!(el === event.target || el.contains(event.target))) {
// Invoke the callback provided in the directive value
binding.value(event);
}
};
// Attach listener to body
document.addEventListener('click', el.clickOutsideEvent);
},
unmounted(el) {
// Clean up the listener to prevent memory leaks
document.removeEventListener('click', el.clickOutsideEvent);
}
};
Usage:
<template>
<button @click="isOpen = true">Open Menu</button>
<!-- If isOpen is true, clicking outside this div will set it to false -->
<div v-if="isOpen" v-click-outside="closeMenu" class="dropdown">
<p>Menu Content...</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { vClickOutside } from './directives/clickOutside';
const isOpen = ref(false);
const closeMenu = () => isOpen.value = false;
</script>
2. The "Long Press" Directive
Handling a long press involves timing. We need to distinguish between a normal click and holding down (for mobile/touch contexts or secondary actions).
directives/longPress.js
export const vLongPress = {
mounted(el, binding) {
let pressTimer = null;
// How long to hold (default 1000ms, or use arg like v-long-press:500)
const duration = parseInt(binding.arg) || 1000;
const start = (e) => {
if (e.type === 'click' && e.button !== 0) return; // Only left click
if (pressTimer === null) {
pressTimer = setTimeout(() => {
// Run the handler
binding.value(e);
}, duration);
}
};
const cancel = () => {
if (pressTimer !== null) {
clearTimeout(pressTimer);
pressTimer = null;
}
};
// Add event listeners for both Mouse and Touch interactions
el.addEventListener('mousedown', start);
el.addEventListener('touchstart', start);
// Cancel on release or movement
el.addEventListener('click', cancel);
el.addEventListener('mouseout', cancel);
el.addEventListener('touchend', cancel);
el.addEventListener('touchcancel', cancel);
},
// Note: In a real app, you should remove these listeners in 'unmounted'
unmounted(el) {
// ... removeEventListeners code here
}
};
Usage:
<template>
<!-- Triggered after holding for 800ms -->
<button v-long-press:800="handleLongPress">
Hold me
</button>
</template>
<script setup>
import { vLongPress } from './directives/longPress';
const handleLongPress = () => alert('Item deleted!');
</script>
3. The "Intersection" Directive (Scroll Animation)
This uses the native IntersectionObserver API to trigger logic when an element enters the viewport (useful for lazy loading images or triggering 'fade-in' animations).
directives/intersect.js
export const vIntersect = {
mounted(el, binding) {
const options = {
root: null,
threshold: 0.5 // Trigger when 50% of element is visible
};
const callback = (entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// Add a CSS class for animation
el.classList.add('animate-in');
// If a function was passed, run it
if (typeof binding.value === 'function') {
binding.value();
}
// Optional: Stop observing once triggered (if 'once' modifier is present)
if (binding.modifiers.once) {
observer.unobserve(el);
}
}
});
};
const observer = new IntersectionObserver(callback, options);
observer.observe(el);
// Save observer on element to access it in unmounted
el._observer = observer;
},
unmounted(el) {
if (el._observer) {
el._observer.disconnect();
}
}
};
Usage:
<template>
<div class="spacer">Scroll Down...</div>
<!-- Adds 'animate-in' class and logs to console once on entry -->
<div v-intersect.once="onEnter" class="box">
I animate when visible
</div>
</template>
<style>
.box { opacity: 0; transition: opacity 1s; }
.box.animate-in { opacity: 1; }
</style>
<script setup>
import { vIntersect } from './directives/intersect';
const onEnter = () => console.log('Element is visible');
</script>
How to Register Globally
If you use these directives in many places, handle registration in main.js so you don't have to import them in every component.
main.js
import { createApp } from 'vue';
import App from './App.vue';
import { vClickOutside } from './directives/clickOutside';
import { vLongPress } from './directives/longPress';
const app = createApp(App);
// Register globally
app.directive('click-outside', vClickOutside);
app.directive('long-press', vLongPress);
app.mount('#app');
Vue 3 Directive Lifecycle Cheatsheet
When implementing your own, remember the Vue 3 hook name changes from Vue 2:
created: Called before attributes or event listeners are applied.
beforeMount: Called when the directive is first bound to the element.
mounted: Called after the parent component's element has been mounted (The most common hook).
beforeUpdate: Called before the containing component's VNode is updated.
updated: Called after the containing component's VNode and its children have updated.
beforeUnmount: Called before the parent component is unmounted.
unmounted: Called after the parent component is unmounted (Clean up listeners here).