Custom directives
Writing your own v- attributes for low-level DOM behavior, the Vue 3 directive hooks, the binding object, and when a composable is the better tool.
Custom directives
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A custom directive packages direct DOM manipulation for a single element so it can be reused as a v- attribute in any template, which is a different job from a composable's reusable stateful logic.
- In <script setup>, any camelCase variable whose name starts with v, such as vFocus, can be used in the template as v-focus; app.directive registers a directive for the whole app.
- A directive object can implement created, beforeMount, mounted, beforeUpdate, updated, beforeUnmount, and unmounted, and a plain function is shorthand for the same behavior in mounted and updated.
- Every hook receives the element and a binding object whose value, oldValue, arg, and modifiers carry whatever the template wrote in v-name:arg.modifier="value".
- One directive definition is shared by every element that uses it, so per-element state such as an event handler to remove later must be stored on the element or in a WeakMap, not in a variable inside the definition.
- The Vue docs recommend directives only when the behavior needs direct DOM access, and advise against using them on components, where they apply to the root element and are ignored with a warning if there are several.
The problem: DOM behavior that keeps getting copied
Some reusable behavior isn’t really about state. It’s about one element: focus this input when it appears, close this panel when someone clicks outside it, show a tooltip on hover, lazy-load this image when it scrolls into view. Each of these needs the actual DOM node and a few lines of imperative code.
You already know one way to get the node: a template ref plus onMounted. It works, but it takes three pieces per element: declare the ref, bind it in the template, write the hook. Put an autofocus on five forms and you’ve written that wiring five times.
Vue’s built-in directives (v-show, v-model, v-on) are exactly this kind of element-level behavior written once and attached as an attribute. Custom directives let you add your own to that list.
Your first directive
A directive is an object of hooks that receive the element:
<script setup>
// The v prefix plus camelCase is what makes this a directive.
const vFocus = {
mounted: (el) => el.focus(),
}
</script>
<template>
<input v-focus placeholder="Starts focused" />
</template>
In <script setup>, any variable named v followed by a capital letter is available in the template under its kebab-case name: vFocus becomes v-focus, vClickOutside becomes v-click-outside. Without <script setup>, you list it under the directives option instead.
To use a directive everywhere, register it on the app, typically from its own file:
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import { vFocus } from './directives/focus'
createApp(App).directive('focus', vFocus).mount('#app')
That local-then-global progression is what the video walks through.
The hooks
A directive object can implement any of seven hooks. The names deliberately mirror component lifecycle hooks, but they fire for the element the directive is on:
const vExample = {
created(el, binding, vnode) {}, // before the element's attributes and listeners are applied
beforeMount(el, binding, vnode) {}, // before the element is inserted into the DOM
mounted(el, binding, vnode) {}, // element and its children are mounted, and so is the parent component
beforeUpdate(el, binding, vnode, prevVnode) {}, // before the containing component updates
updated(el, binding, vnode, prevVnode) {}, // after the containing component and its children update
beforeUnmount(el, binding, vnode) {},
unmounted(el, binding, vnode) {}, // the place to clean up
}
Most directives need two or three. mounted sets things up, updated reacts to a new value, unmounted tears down whatever mounted created.
If you want the same behavior on mount and on every update, and nothing else, pass a function instead of an object:
// Function shorthand: runs in mounted and updated.
const vColor = (el, binding) => {
el.style.color = binding.value
}
If you’ve read Vue 2 code, the hook names changed: bind is now beforeMount, inserted is mounted, componentUpdated is updated, unbind is unmounted, and Vue 2’s update hook is gone. A tutorial using the old names is teaching Vue 2.
The binding object: value, argument, modifiers
A directive in a template can carry three kinds of input, and each one has its place on binding:
<p v-pin:left.animate="40">Pinned</p>
<!-- ^arg ^modifier ^value -->
const vPin = {
mounted(el, binding) {
// binding.arg -> 'left'
// binding.modifiers -> { animate: true }
// binding.value -> 40
el.style.position = 'fixed'
el.style[binding.arg || 'top'] = `${binding.value}px`
if (binding.modifiers.animate) el.style.transition = 'all 0.2s'
},
updated(el, binding) {
if (binding.value !== binding.oldValue) {
el.style[binding.arg || 'top'] = `${binding.value}px`
}
},
}
The value is any JavaScript expression, so you can pass an object literal (v-pin="{ side: 'left', offset: 40 }") when you need more than one setting. The argument can be dynamic with square brackets, v-pin:[side]="40", just like v-bind:[name]. binding.oldValue is only available in beforeUpdate and updated.
A real directive with cleanup: v-click-outside
Here’s a directive that calls a function whenever a click lands outside its element:
// directives/clickOutside.js
const handlers = new WeakMap()
export const vClickOutside = {
mounted(el, binding) {
const handler = (event) => {
if (!el.contains(event.target)) binding.value(event)
}
handlers.set(el, handler)
document.addEventListener('click', handler)
},
unmounted(el) {
document.removeEventListener('click', handlers.get(el))
handlers.delete(el)
},
}
<div v-if="open" v-click-outside="() => (open = false)">Menu</div>
Two details matter here. First, cleanup: the listener is on document, which outlives the element. Without unmounted, every time the menu opens and closes you’d leak another listener. Second, per-element state: the directive object is one shared definition, used by every element that has v-click-outside. A plain let handler inside the module would be overwritten by the second element, so the handler is keyed by element in a WeakMap (see Map, Set, and weak collections). The WeakMap won’t keep a detached element alive after it’s gone.
Typing directives
With TypeScript, the Directive type takes the element type and the value type:
import type { Directive } from 'vue'
export const vColor: Directive<HTMLElement, string> = (el, binding) => {
el.style.color = binding.value // string
}
For globally registered directives, augment ComponentCustomProperties so templates type-check them:
declare module 'vue' {
interface ComponentCustomProperties {
vColor: typeof vColor
}
}
This is TypeScript module augmentation; the Lachlan Miller video under Go deeper builds a typed directive step by step.
Directive or composable?
The VueUse lesson showed onClickOutside, a composable that does what v-click-outside does. So which should you write?
- Use a directive when the behavior is about one element, needs no state the component reads back, and reads best as markup:
v-focus,v-tooltip="'Copy'",v-lazy-src="url". - Use a composable when the component needs something back (a ref, a
stopfunction, reactive state) or when the logic isn’t tied to a single element.
The Vue docs add a sharper rule: reach for a custom directive only when the behavior needs direct DOM manipulation. If a v-bind or a class binding can express it, use that, because built-ins are more efficient and work with server rendering. Custom directive hooks don’t run on the server; a directive that must render something during SSR can implement getSSRProps to return attributes.
Avoid putting custom directives on components. A directive on a component applies to its root element, the same way fallthrough attributes do. Unlike attributes, a directive can’t be passed to a different element with v-bind="$attrs", and if the component has more than one root node, Vue ignores the directive and warns.
What the video covers
Danny’s video, part of a Vue 3 Composition API series, builds an autofocus directive the way this lesson starts: first as a local, v-prefixed constant in <script setup>, then moved to its own file and registered globally with app.directive. It’s short and uses current Vue 3 syntax throughout. The binding object, update and cleanup hooks, per-element state, and the directive-versus-composable choice aren’t in the video, so the lesson covers them.
Where this fits
app.directive is one of several things an app instance can register globally. Bundling those registrations into a reusable package is what plugins are for.
Check yourself
In <script setup>, you write const focusOnMount = { mounted: (el) => el.focus() }. Why can't the template use it as v-focus-on-mount?
<script setup> only treats a variable as a directive when its name starts with a lowercase v followed by a capital letter, such as vFocusOnMount. Renaming it to vFocusOnMount makes it available as v-focus-on-mount.
For <input v-format:currency.round="price" />, what does the binding object contain in the mounted hook?
binding.arg is 'currency', binding.modifiers is { round: true }, and binding.value is the current value of price. On updates, binding.oldValue holds the previous value.
A v-click-outside directive adds a document click listener in mounted. Why is const handler = ... declared inside the directive definition object a bug, and what should you do instead?
The definition object is created once and shared by every element using the directive, so a single variable would be overwritten by the second element and the first element's listener could never be removed. Store the handler per element, for example on el itself or in a WeakMap keyed by el, and remove that specific handler in unmounted.
Vue 2 directives used bind, inserted, and unbind. What are the Vue 3 equivalents?
bind became beforeMount, inserted became mounted, and unbind became unmounted. componentUpdated became updated, Vue 2's update hook was removed, and Vue 3 added created, beforeUpdate, and beforeUnmount to match component lifecycle names.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.