<template>
<div id="app">
<h1>Sherlock's Custom Vue 3 Directives: Unraveling Complex User Interactions</h1>
<!-- Example 1: v-draggable - Drag and drop for repositionable elements -->
<div class="demo-section">
<h2>1. Draggable Directive (v-draggable)</h2>
<div v-draggable="dragOptions" class="draggable-box">
Drag me around! Position: {{ dragPosition.x }}, {{ dragPosition.y }}
</div>
</div>
<!-- Example 2: v-ripple - Material Design ripple effect on interactions -->
<div class="demo-section">
<h2>2. Ripple Effect (v-ripple)</h2>
<button v-ripple class="ripple-btn">Click for Ripple!</button>
<div v-ripple class="ripple-div" @click="handleDivClick">Div with Ripple</div>
</div>
<!-- Example 3: v-intersection - Trigger actions on viewport intersection (e.g., lazy load, animations) -->
<div class="demo-section">
<h2>3. Intersection Observer (v-intersection)</h2>
<div class="spacer"></div>
<div
v-intersection="intersectionCallback"
class="intersection-box"
>
Scroll to intersect me! Visible: {{ isVisible }}
</div>
<div class="spacer"></div>
</div>
<!-- Example 4: v-longpress - Handle long press gestures -->
<div class="demo-section">
<h2>4. Long Press (v-longpress="longPressHandler")</h2>
<div v-longpress="longPressHandler" class="longpress-box">
Long press me (800ms)!
</div>
</div>
<!-- Example 5: v-auto-focus - Complex focus management with conditions -->
<input v-auto-focus="shouldAutoFocus" placeholder="Auto-focus me?" />
<button @click="shouldAutoFocus = !shouldAutoFocus">Toggle Auto-Focus</button>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
// Reactive data for examples
const dragPosition = ref({ x: 0, y: 0 })
const dragOptions = ref({ handler: '.handle' }) // Optional: drag only by handle
const isVisible = ref(false)
const shouldAutoFocus = ref(true)
// Handlers
const intersectionCallback = (el, visible) => {
isVisible.value = visible
if (visible) {
el.style.opacity = '1'
el.style.transform = 'translateY(0)'
}
}
const handleDivClick = () => console.log('Div clicked!')
const longPressHandler = (el) => {
console.log('Long press detected on:', el)
el.style.backgroundColor = '#ff6b6b'
}
// Directive definitions will be registered globally below
</script>
<style scoped>
#app { padding: 20px; font-family: Arial, sans-serif; }
.demo-section { margin: 30px 0; border: 1px solid #ddd; padding: 20px; }
.draggable-box {
width: 200px; height: 100px; background: #4CAF50; color: white;
display: flex; align-items: center; justify-content: center; cursor: move;
position: relative; user-select: none;
}
.draggable-box .handle { position: absolute; top: 5px; right: 5px; cursor: move; }
.ripple-btn, .ripple-div {
padding: 15px 30px; background: #2196F3; color: white; border: none;
border-radius: 4px; cursor: pointer; margin: 10px; display: inline-block;
}
.intersection-box {
height: 200px; background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
color: white; display: flex; align-items: center; justify-content: center;
opacity: 0; transform: translateY(50px); transition: all 0.5s;
}
.spacer { height: 300px; background: #f0f0f0; }
.longpress-box {
width: 200px; height: 100px; background: #FFC107; display: flex;
align-items: center; justify-content: center; cursor: pointer;
transition: background 0.3s;
}
</style>
Directive Implementations (Register Globally)
Add these before your app mount in main.js (or use defineDirective in Vue 3.3+ for local directives). Here's the detective work: these directives hook into Vue's lifecycle (mounted, updated, etc.) to handle DOM-level interactions efficiently, bypassing the need for bulky components.
// main.js
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 1. v-draggable: Full drag-and-drop with optional handle
app.directive('draggable', {
mounted(el, binding) {
const handler = binding.value?.handler ? el.querySelector(binding.value.handler) : el
let pos = { x: 0, y: 0 }
let startPos = { x: 0, y: 0 }
let dragging = false
const dragStart = (e) => {
dragging = true
startPos = { x: e.clientX, y: e.clientY }
pos = { x: parseInt(el.style.left || 0), y: parseInt(el.style.top || 0) }
document.addEventListener('mousemove', dragMove)
document.addEventListener('mouseup', dragEnd)
}
const dragMove = (e) => {
if (!dragging) return
const dx = e.clientX - startPos.x
const dy = e.clientY - startPos.y
el.style.left = `${pos.x + dx}px`
el.style.top = `${pos.y + dy}px`
el.style.position = 'fixed'
// Update reactive data if bound
if (binding.value?.onDrag) binding.value.onDrag({ x: pos.x + dx, y: pos.y + dy })
}
const dragEnd = () => {
dragging = false
document.removeEventListener('mousemove', dragMove)
document.removeEventListener('mouseup', dragEnd)
}
handler.addEventListener('mousedown', dragStart)
el._dragHandler = handler // Store for cleanup
},
unmounted(el) {
if (el._dragHandler) {
el._dragHandler.removeEventListener('mousedown', el._dragHandler._dragStart)
}
}
})
// 2. v-ripple: Ink ripple effect on pointer events
app.directive('ripple', {
mounted(el) {
el.style.overflow = 'hidden'
el.style.position = 'relative'
const createRipple = (event) => {
const ripple = document.createElement('span')
const rect = el.getBoundingClientRect()
const size = Math.max(rect.width, rect.height)
const x = event.clientX - rect.left - size / 2
const y = event.clientY - rect.top - size / 2
ripple.style.width = ripple.style.height = `${size}px`
ripple.style.left = `${x}px`
ripple.style.top = `${y}px`
ripple.classList.add('ripple')
el.appendChild(ripple)
setTimeout(() => ripple.remove(), 600)
}
el.addEventListener('pointerdown', createRipple)
el._rippleListener = createRipple
},
unmounted(el) {
if (el._rippleListener) el.removeEventListener('pointerdown', el._rippleListener)
}
})
// Add CSS for ripple in global styles
// .ripple { position: absolute; border-radius: 50%; background: rgba(255,255,255,0.6); transform: scale(0); animation: ripple 0.6s linear; }
// @keyframes ripple { to { transform: scale(4); opacity: 0; } }
// 3. v-intersection: Intersection Observer API wrapper
app.directive('intersection', {
mounted(el, binding) {
const callback = binding.value
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => callback(entry.target, entry.isIntersecting))
}, { threshold: 0.1 })
observer.observe(el)
el._intersectionObserver = observer
},
unmounted(el) {
if (el._intersectionObserver) el._intersectionObserver.disconnect()
}
})
// 4. v-longpress: Detect long press (default 800ms)
app.directive('longpress', {
mounted(el, binding) {
let timer = null
let startX, startY
const startPress = (e) => {
startX = e.clientX
startY = e.clientY
timer = setTimeout(() => {
if (Math.abs(e.clientX - startX) < 10 && Math.abs(e.clientY - startY) < 10) {
binding.value(el)
}
}, 800)
}
const cancelPress = () => {
clearTimeout(timer)
}
el.addEventListener('pointerdown', startPress)
el.addEventListener('pointermove', cancelPress)
el.addEventListener('pointerup', cancelPress)
el.addEventListener('pointerleave', cancelPress)
el._pressListeners = { startPress, cancelPress }
},
unmounted(el) {
if (el._pressListeners) {
Object.values(el._pressListeners).forEach(fn => {
el.removeEventListener('pointerdown', fn)
el.removeEventListener('pointermove', fn)
el.removeEventListener('pointerup', fn)
el.removeEventListener('pointerleave', fn)
})
}
}
})
// 5. v-auto-focus: Conditional auto-focus with Vue reactivity
app.directive('auto-focus', {
mounted(el, binding) {
if (binding.value) el.focus()
},
updated(el, binding) {
if (binding.value) el.focus()
}
})
app.mount('#app')
The Case Closed: Why These Directives?
- Performance: DOM-direct manipulation, no virtual DOM overhead for interactions.
- Reusability: Drop
v-draggable anywhere—no props drilling.
- Hooks: Leverage lifecycle (
mounted, updated, unmounted) for cleanup.
- Bindings: Pass objects/functions (e.g.,
{ onDrag: handler }) for complexity.
- Edge Cases: Handles mobile (pointer events), cleanup prevents leaks.
Test in a Vue 3 sandbox (e.g., StackBlitz). Need more? A v-resize or v-copy directive? Just say the word, Watson. 🔍