Skip to main content
InterviewHubPRO
Section Overview
Q37

Question 37 of 50

Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)

74%
Vue.js & Composition API (50 Qs)•Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)

Custom Directives in Vue 3: Lifecycle Hooks and Practical Implementations.

senior LevelCode ExampleDirectivesHooksLifecycle

In Simple Words: Custom Directives allow direct low-level DOM manipulations on elements. In Vue 3, directive hooks mirror component lifecycles (created, beforeMount, mounted, beforeUpdate, updated, beforeUnmount, unmounted).

typescript
// v-click-outside directive implementation
import { Directive } from 'vue';

export const vClickOutside: Directive = {
  mounted(el, binding) {
    el._clickOutsideHandler = (event: MouseEvent) => {
      if (!(el === event.target || el.contains(event.target as Node))) {
        binding.value(event); // Invoke passed callback
      }
    };
    document.addEventListener('click', el._clickOutsideHandler);
  },
  unmounted(el) {
    document.removeEventListener('click', el._clickOutsideHandler);
  }
};

// Usage in template:
// <div v-click-outside="closeDropdown">...</div>