LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 2814 min read

Custom Directives

Build your own reusable, low-level DOM behavior — like an auto-focus or click-outside directive — with custom directives.

When to Reach for a Custom Directive

Custom directives are for reusable, low-level DOM manipulation that doesn't fit naturally into a component — things like auto-focusing an element, or detecting a click outside it. If the behavior involves meaningful UI and state, a component is usually the better fit; if it's purely about an element's raw DOM behavior, a directive is.

Defining a Local Directive

A directive prefixed with v inside <script setup> is automatically usable in the template with a v- prefix.

<script setup>
const vFocus = {
mounted: (el) => el.focus(),
};
</script>
<template>
<input v-focus />
</template>

Directive Hooks

A directive is an object with hooks that mirror the component lifecycle, each receiving the actual DOM element as their first argument.

HookRuns When
mountedThe bound element is inserted into the DOM
updatedThe containing component re-renders
unmountedThe bound element is removed from the DOM

A Click-Outside Directive

A classic real-world use — closing a dropdown or modal when the user clicks anywhere outside of it.

<script setup>
const vClickOutside = {
mounted(el, binding) {
el._clickOutsideHandler = (event) => {
if (!el.contains(event.target)) {
binding.value(event); // call the handler passed to the directive
}
};
document.addEventListener('click', el._clickOutsideHandler);
},
unmounted(el) {
document.removeEventListener('click', el._clickOutsideHandler);
},
};
</script>
<template>
<div v-click-outside="closeDropdown">Dropdown content</div>
</template>
binding.value

Whatever expression you pass to a directive (v-click-outside="closeDropdown") is available inside its hooks as binding.value — this is how a directive accepts configuration or a callback from the component using it.

FAQs

Yes — app.directive('focus', {...}) on the app instance in main.js registers it globally, similar to a globally registered component.

Less common than components and composables — most needs are covered by those two, and custom directives are reserved for genuinely low-level DOM behavior.

Summary

Custom directives give you reusable, low-level DOM behavior via lifecycle-style hooks, for the cases components and composables don't naturally fit. Next, you'll learn Teleport, for rendering content outside a component's normal DOM position.

Next Lesson →

Teleport