Tutorials Logic, IN info@tutorialslogic.com

Vue Custom Directives v focus, v click outside: Tutorial, Examples, FAQs & Interview Tips

Vue Custom Directives v focus, v click outside

Vue in Vue is best learned by connecting the rule to a small admin screen. Start with the smallest component or composable, observe the output, and then add one realistic constraint so the concept becomes practical.

The key habit for this lesson is to watch ref, prop, slot, or emitted event as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.

What are Custom Directives?

Custom directives let you directly manipulate DOM elements in a reusable way. While components are for reusing UI logic, custom directives are for reusing low-level DOM manipulation - things like auto-focus, click-outside detection, tooltips, and lazy loading.

Hook When called
created Before element's attributes/event listeners are applied
beforeMount Before element is inserted into DOM
mounted After element is inserted into DOM
beforeUpdate Before the component updates
updated After the component and children update
beforeUnmount Before element is removed
unmounted After element is removed

Custom Directives - v-focus, v-click-outside, v-tooltip, v-lazy

Custom Directives - v-focus, v-click-outside, v-tooltip, v-lazy
// directives/index.js

// v-focus - auto-focus an input
export const vFocus = {
    mounted(el) {
        el.focus()
    }
}

// v-click-outside - detect clicks outside an element
export const vClickOutside = {
    mounted(el, binding) {
        el._clickOutsideHandler = (event) => {
            if (!el.contains(event.target)) {
                binding.value(event)  // call the provided function
            }
        }
        document.addEventListener('click', el._clickOutsideHandler)
    },
    unmounted(el) {
        document.removeEventListener('click', el._clickOutsideHandler)
    }
}

// v-tooltip - show tooltip on hover
export const vTooltip = {
    mounted(el, binding) {
        const tooltip = document.createElement('div')
        tooltip.className = 'tooltip'
        tooltip.textContent = binding.value
        tooltip.style.cssText = `
            position: absolute; background: #333; color: white;
            padding: 4px 8px; border-radius: 4px; font-size: 12px;
            pointer-events: none; opacity: 0; transition: opacity 0.2s;
            white-space: nowrap; z-index: 1000;
        `
        document.body.appendChild(tooltip)

        el._tooltip = tooltip
        el._showTooltip = () => {
            const rect = el.getBoundingClientRect()
            tooltip.style.left = rect.left + 'px'
            tooltip.style.top  = (rect.top - 30 + window.scrollY) + 'px'
            tooltip.style.opacity = '1'
        }
        el._hideTooltip = () => { tooltip.style.opacity = '0' }

        el.addEventListener('mouseenter', el._showTooltip)
        el.addEventListener('mouseleave', el._hideTooltip)
    },
    updated(el, binding) {
        el._tooltip.textContent = binding.value
    },
    unmounted(el) {
        el.removeEventListener('mouseenter', el._showTooltip)
        el.removeEventListener('mouseleave', el._hideTooltip)
        el._tooltip.remove()
    }
}

// v-lazy - lazy load images
export const vLazy = {
    mounted(el, binding) {
        const observer = new IntersectionObserver(([entry]) => {
            if (entry.isIntersecting) {
                el.src = binding.value
                observer.disconnect()
            }
        }, { threshold: 0.1 })
        observer.observe(el)
        el._observer = observer
    },
    unmounted(el) {
        el._observer?.disconnect()
    }
}

// v-highlight - highlight text
export const vHighlight = {
    mounted(el, binding) {
        el.style.backgroundColor = binding.value || 'yellow'
    },
    updated(el, binding) {
        el.style.backgroundColor = binding.value || 'yellow'
    }
}

// Register globally in main.js:
// app.directive('focus', vFocus)
// app.directive('click-outside', vClickOutside)
// app.directive('tooltip', vTooltip)

What are Custom Directives?

What are Custom Directives?
<template>
  <div>
    <!-- v-focus - auto-focus on mount -->
    <input v-focus placeholder="I'm auto-focused!" />

    <!-- v-click-outside - close dropdown when clicking outside -->
    <div class="dropdown" v-click-outside="closeDropdown">
      <button @click="isOpen = !isOpen">Menu</button>
      <ul v-if="isOpen">
        <li>Option 1</li>
        <li>Option 2</li>
      </ul>
    </div>

    <!-- v-tooltip - show tooltip on hover -->
    <button v-tooltip="'Click to save your changes'">Save</button>
    <button v-tooltip="tooltipText">Dynamic tooltip</button>

    <!-- v-lazy - lazy load image -->
    <img v-lazy="'/images/large-photo.jpg'" alt="Lazy loaded" />

    <!-- v-highlight with value -->
    <p v-highlight="'#ffeb3b'">This text is highlighted yellow</p>
    <p v-highlight="'#e3f2fd'">This text is highlighted blue</p>

    <!-- Local directive (in <script setup>, prefix with v) -->
    <input v-auto-resize />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { vFocus, vClickOutside, vTooltip, vLazy, vHighlight } from '@/directives'

const isOpen = ref(false)
const tooltipText = ref('Hello from Vue!')

function closeDropdown() {
  isOpen.value = false
}

// Local directive - defined in <script setup>, no registration needed
// Just name it vSomething and use as v-something
const vAutoResize = {
  mounted(el) {
    el.style.resize = 'none'
    el.style.overflow = 'hidden'
    const resize = () => {
      el.style.height = 'auto'
      el.style.height = el.scrollHeight + 'px'
    }
    el.addEventListener('input', resize)
    el._resize = resize
  },
  unmounted(el) {
    el.removeEventListener('input', el._resize)
  }
}
</script>

Deep Dive: Custom Directives in Real Projects

Understanding Custom Directives is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Custom Directives.

A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.

Common Mistakes to Avoid

  • Mixing too many responsibilities in one component instead of separating logic by concern.
  • Skipping meaningful naming for variables, emits, and component props.
  • Ignoring edge cases like empty data, loading states, and error handling.
  • Optimizing too early before measuring real bottlenecks in browser devtools.
  • Not creating small test scenarios to validate behavior after each change.

Mini Practice Checklist

  • Build a small demo focused only on Custom Directives.
  • Add one edge case (empty/loading/error) and handle it cleanly.
  • Refactor repeated logic into a reusable function/composable.
  • Add clear comments only where logic is non-obvious.
  • Verify behavior with manual testing and Vue Devtools.

Applied guide for Vue

Use Vue when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real Vue task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.

A reliable practice flow is: create the smallest working component or composable, add one normal case, add one edge case such as missing, repeated, empty, or boundary input, and then confirm the result with Vue Devtools and template warnings. If the result surprises you, reduce the code until the behavior is visible again.

The most common trap here is copying the syntax before understanding the behavior. Avoid it by writing one sentence before the code that explains why Vue is the right choice. After the code runs, verify the lesson by doing this: change one input and explain the changed output.

  • Identify the exact problem solved by Vue.
  • Trace ref, prop, slot, or emitted event before and after the main operation.
  • Keep one intentionally broken version and explain the fix.
  • Connect the example to a small admin screen so the idea feels concrete.
Key Takeaways
  • I can explain where Vue fits inside a small admin screen.
  • I can point to the exact ref, prop, slot, or emitted event affected by this topic.
  • I tested a normal case and an edge case involving missing, repeated, empty, or boundary input.
  • I verified the result with Vue Devtools and template warnings instead of assuming it worked.
  • I can describe the main mistake: copying the syntax before understanding the behavior.
Common Mistakes to Avoid
WRONG Copying the syntax before understanding the behavior.
RIGHT Write the expected behavior first, then make the example prove it.
A one-line expectation turns the code from copied syntax into a testable idea.
WRONG Practicing only the perfect input.
RIGHT Also test missing, repeated, empty, or boundary input before considering the lesson complete.
The edge case is where most interview follow-up questions begin.
WRONG Looking only at the final output.
RIGHT Trace ref, prop, slot, or emitted event through each important step.
Tracing makes debugging faster because you can see the first incorrect state.

Practice Tasks

  • Build one small component or composable that demonstrates Vue in a small admin screen.
  • Change the example to include missing, repeated, empty, or boundary input and record the difference.
  • Break the example by deliberately copying the syntax before understanding the behavior, then write the corrected version.
  • Explain the finished example in five bullet points: input, operation, output, failure case, and verification.

Frequently Asked Questions

Use it when the problem matches the behavior shown in the example and when the result can be verified through Vue Devtools and template warnings.

Start with a tiny case, then test missing, repeated, empty, or boundary input. The main warning sign is copying the syntax before understanding the behavior.

Trace ref, prop, slot, or emitted event, predict the result, run the example, and compare your prediction with the actual output.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.