The user wants to know how to implement custom directives in Vue 3 to handle complex user interactions.
1. Understand the Goal:
* Topic: Vue 3 Custom Directives.
* Specific Use Case: Complex user interactions (beyond simple attribute manipulation, likely involving DOM events, state, and cleanup).
* Framework Version: Vue 3 (Syntax differs from Vue 2, specifically regarding hook names and the vnode structure).
2. Key Concepts to Cover:
* Registration: Global vs. Local.
* Hook Functions:created, beforeMount, mounted, beforeUpdate, updated, beforeUnmount, unmounted.
* Hook Arguments:el, binding (value, oldValue, arg, modifiers), vnode, prevVNode.
* Complex Interaction Examples:
* Click Outside: A classic use case. Closing modals/dropdowns.
* Long Press: Handling a press-and-hold gesture (touch/mouse).
* Draggable: Making an element movable.
* Debounce/Throttle: optimizing input handling (though composable functions are often preferred now, a directive approach is still a valid "interaction" pattern for some).
3. Structuring the Guide:
code
* **Introduction:** Briefly explain what custom directives are and when to use them (low-level DOM access).
* **Anatomy of a Directive:** Show the object structure with hooks.
* **Example 1: The "Click Outside" Directive (The foundational complex interaction):**
* *Logic:* Add event listener on mount, check `contains` on click, remove listener on unmount.
* *Code:* Vue 3 syntax (`onUnmounted` inside `mounted`? No, use directive hooks).
* **Example 2: The "Long Press" Directive (Gesture handling):**
* *Logic:* Start timer on `mousedown`/`touchstart`, clear on `mouseup`/`touchend`. Trigger callback if threshold met.
* *Complexity:* Needs to handle arguments (duration) and maybe modifiers.
* **Example 3: "Draggable" (Stateful interaction):**
* *Logic:* Track position, update styles. This demonstrates handling dynamic updates (`updated` hook might be needed if config changes, but mostly DOM events).
* **Best Practices:**
* When to use directives vs. Components.
* Passing functions vs. values.
* TypeScript support.
4. Drafting the Content (Iterative Refinement):
code
* *Refining the Hook Map:*
* Vue 2: `bind`, `inserted`, `update`, `componentUpdated`, `unbind`.
* Vue 3: `created`, `beforeMount`, `mounted`, `beforeUpdate`, `updated`, `beforeUnmount`, `unmounted`.
* *Self-Correction:* I must ensure I strictly use Vue 3 naming. Most logic usually goes in `mounted` and `unmounted` for event listeners.
* *Example 1 (Click Outside):*
* Need a handler function.
* Attach to `document`.
* Check `el.contains(event.target)`.
* Execute `binding.value`.
* *Example 2 (Long Press):*
* This is good because it involves timers.
* `mousedown` -> start timer.
* `mouseup` -> clear timer.
* If timer finishes -> call `binding.value`.
* *Nuance:* Need to handle both mouse and touch events for mobile compatibility.
* *Passing Data:* Show how to pass a callback function `v-directive="callback"` and arguments `v-directive:arg.modifiers="value"`.
5. Writing the Code Snippets (Mental Draft -> Code):
code
* *Setup:* `<script setup>` is the standard now. I should show how to register locally in `<script setup>` or globally in `main.js`.
* *Code Structure:*
```javascript
const vClickOutside = {
mounted(el, binding) {
el._clickOutside = (event) => {
if (!(el === event.target || el.contains(event.target))) {
binding.value(event);
}
};
document.addEventListener('click', el._clickOutside);
},
unmounted(el) {
document.removeEventListener('click', el._clickOutside);
}
};
```
6. Adding "Complex" Flavor:
The prompt asks for "complex interactions." A simple one-liner isn't enough. I should include:
1. Argument passing:v-long-press:500="doSomething".
2. Cleanup: Essential for preventing memory leaks in complex apps.
3. Reactivity: Updating the directive if the binding changes (though less common for pure interactions, good to mention).
7. Final Review of the Plan:
* Intro: Concept & Hook Names.
* Scenario 1 (Click Outside): Standard modal/dropdown logic.
* Scenario 2 (Long Press): Touch/Gesture logic with dynamic arguments.
* Scenario 3 (Draggable): Continuous state updates.
* Registration: Global vs Local.
* Comparison: Components vs Directives.
8. Generating the Response: (Proceeding to generate the actual response based on these steps). Self-correction during generation: Ensure I explicitly mention binding.instance if accessing component context is needed, though usually, we just execute the callback passed via value.
Let's refine the Long Press example to be robust. It should accept a duration via argument.
v-long-press:500="handlePress" -> binding.arg is '500'.
Let's write it out.
Step 1: Basics. Explain the API changes (Vue 3 hooks).
Step 2: v-click-outside. The most practical interaction directive.
Step 3: v-long-press. Good for illustrating arguments and timers.
Step 4: v-draggable. Good for illustrating DOM manipulation.
Step 5: TypeScript/Reusability tips.
The response looks solid. I will format it clearly with code blocks and explanations.
In Vue 3, custom directives are designed to encapsulate low-level DOM manipulations that cannot be easily achieved with standard template syntax. While Vue 2 focused on lifecycle hooks like bind and update, Vue 3 aligns directive hooks with the component lifecycle, making them more intuitive.
Here is a comprehensive guide to implementing custom directives for complex user interactions in Vue 3.
1. The Anatomy of a Vue 3 Directive
A custom directive is an object containing lifecycle hooks. The hooks receive the element (el) and a binding object (binding) which contains the value, arguments, and modifiers passed to the directive.
Available Hooks:
created: Before the element's attributes or event listeners are applied.
beforeMount: When the directive is bound to the element (replaces Vue 2 bind).
mounted: When the parent component is mounted (replaces Vue 2 inserted).
beforeUpdate: Before the parent component updates.
updated: After the parent component updates (replaces Vue 2 componentUpdated).
beforeUnmount: Before the parent component unmounts.
unmounted: When the directive is unbound from the element (replaces Vue 2 unbind).
2. Example 1: The "Click Outside" Directive
This is a classic complex interaction. We want to detect when a user clicks outside of a specific element (like a modal or dropdown) to trigger a close action.
The Logic:
Bind a click listener to the document on mount.
Check if the click target is inside the directive element.
If outside, execute the callback function passed to the directive.
Clean up the listener on unmount.
Implementation:
javascript
// main.js or a dedicated directives.js file
import { createApp } from 'vue'
const clickOutsideDirective = {
mounted(el, binding) {
// binding.value is the function passed to v-click-outside
el._clickOutside = (event) => {
// If the click was inside the element, do nothing
if (el === event.target || el.contains(event.target)) {
return
}
// If click is outside, execute the callback
if (typeof binding.value === 'function') {
binding.value(event)
}
}
// Use setTimeout to prevent the click that opened the modal
// from immediately triggering the close event (event propagation)
setTimeout(() => {
document.addEventListener('click', el._clickOutside)
}, 0)
},
unmounted(el) {
// Crucial: Clean up event listener to prevent memory leaks
document.removeEventListener('click', el._clickOutside)
}
}
const app = createApp({})
app.directive('click-outside', clickOutsideDirective)
Interaction optimization often requires debouncing (limiting the rate at which a function fires). While usually done via composables, a directive is useful for raw DOM events where you want to keep the logic out of the script setup.
The Logic:
Intercept the event specified in the argument (e.g., v-debounce:input).
Wrap the handler in a timeout.
Handle updates to the delay time dynamically.
javascript
const debounceDirective = {
mounted(el, binding) {
const event = binding.arg || 'click' // Default to click
const handler = binding.value
const delay = 500 // Default delay
let timer = null
el._debouncedHandler = (e) => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
handler(e)
}, delay)
}
el.addEventListener(event, el._debouncedHandler)
},
unmounted(el) {
// Use the same event name used in mounted
const event = binding.arg || 'click'
el.removeEventListener(event, el._debouncedHandler)
}
}
5. Registering Directives
You can register directives globally (as shown above in main.js) or locally within a specific component using the <script setup> syntax.
Local Registration (Script Setup):
Any variable starting with v followed by a capital letter (CamelCase) in script setup is automatically available as a custom directive.
Store Data on el: Since hooks share the same element instance, you can store variables (like timer IDs or handler references) directly on the element (e.g., el._timer) to pass state between mounted and unmounted.