Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 87 ยท Reusability, Transitions and Styling

Custom Directives

Write your own Vue 3 directives. Learn the directive hooks, the binding object with value, arg and modifiers, and build v-focus and v-click-outside. Know when a composable is the better tool.

You already use built-in directives such as v-if, v-model and v-bind. A custom directive is your own v-something attribute: a small object with functions that Vue calls at certain moments in an element's life, and that receives the real DOM element. It is the tool for reusable, low-level DOM work that does not fit a component, such as focusing an input, closing a menu when the user clicks elsewhere or attaching a tooltip library to an element.

Most of what you build in Vue is done with components and composables, and those are the right default. Directives are the exception: reach for one only when you need direct access to a plain element. This lesson shows how they work and gives you two practical ones.

The shape of a directive

A directive is an object whose properties are hooks. Every hook is optional, and each receives the element as its first argument:

Hook When it runs
created(el, binding, vnode) Before the element's attributes and listeners are applied
beforeMount Just before the element is inserted into the DOM
mounted After the element and its children are inserted
beforeUpdate Before the containing component re-renders
updated After the containing component and its children have updated
beforeUnmount Just before the element is removed
unmounted After the element is removed

They mirror the component lifecycle hooks, but they belong to one element.

flowchart LR
    A["created"] --> B["beforeMount"]
    B --> C["mounted"]
    C --> D["beforeUpdate"]
    D --> E["updated"]
    E -->|"state changes again"| D
    C --> F["beforeUnmount"]
    E --> F
    F --> G["unmounted"]

A directive's hooks run in this order; the update pair repeats for every re-render of its component.

The second argument, binding, describes how the directive was used:

  • binding.value: the value of the expression, as in v-demo="count + 1".
  • binding.oldValue: the previous value, only in beforeUpdate and updated.
  • binding.arg: the argument after the colon, as in v-demo:size.
  • binding.modifiers: an object of the modifiers, v-demo.bold.italic gives { bold: true, italic: true }.
  • binding.instance: the component instance that uses the directive.

Registering directives

In <script setup>, any camelCase variable that starts with v is available in the template as a directive, so const vFocus = {...} becomes v-focus. This is read-only code on this site, because it needs a build step:

VUE
<script setup>
const vFocus = {
  mounted(el) {
    el.focus();
  },
};
</script>

<template>
  <input v-focus />
</template>

Without <script setup> you register a directive locally with the directives option, or for the whole app with app.directive("focus", vFocus). The examples below use both, because they run without a build step.

A v-focus directive

The browser's autofocus attribute is only reliable for elements that exist when the page loads. For an input that appears later, for example after clicking "Edit", you need to call focus() yourself once the element is in the DOM. That is a one-line job for the mounted hook.

v-focus on an input that appears later

Click Edit: the input is inserted and, thanks to v-focus, you can type immediately without clicking into it. The status line proves that the focus event fired.

A v-click-outside directive

The classic use for a directive: close a dropdown or popover when the user clicks anywhere else. The directive needs a listener on document, and it must remove that listener again when the element goes away, otherwise listeners pile up and leak memory. The hooks give you exactly the right places: set up in mounted, tear down in unmounted.

The value of the directive is a function. It is stored on the element so the updated hook can swap in a new function if the parent passes a different one.

v-click-outside closes a menu

Open the menu and click the dashed box: the menu closes and the counter goes up. Clicking a menu item closes it too, but that is not counted, because the click happened inside the element.

Notice that the directive sits on a wrapper that contains the button as well as the panel. If it were only on the panel, the click that opens the menu would reach document after the panel was inserted, look like an outside click and close the menu again at once. Putting the directive on the element that contains both avoids this bug.

Arguments, modifiers and the function shorthand

Directives can be configured from the template. The argument (:size), the modifiers (.bold) and the value (="n") all arrive in binding. The example registers two directives globally with app.directive. v-inspect writes what it receives into a data-info attribute, which a CSS rule displays after the text. v-paint uses the function shorthand: when you only need the same behavior on mounted and updated, pass a single function instead of an object.

What a directive receives in binding

Press Increase n and watch value and oldValue change together. The first time, oldValue is missing, because it does not exist in mounted. The v-paint directive uses the argument as the CSS property name and the value as the color, so the same directive can paint color, border-color or anything else.

Arguments can also be dynamic, as in v-paint:[property]="color". If you need several values, pass an object literal: v-demo="{ x: 1, y: 2 }".

Rules of thumb

  • Directives are for DOM access. If the work can be done with a prop, a slot, a class binding or a template ref, use that. Logic that only needs reactive state belongs in a composable.
  • Clean up everything. Whatever you add in mounted (listeners, observers, timers) must be removed in unmounted.
  • Do not store state on el casually. A hidden property on the element, like el._outside, is fine for a directive's own bookkeeping, but name it uniquely. A WeakMap keyed by the element is a tidy alternative.
  • Avoid directives on components. A directive applied to a component is attached to its root element, and Vue warns for components with several root nodes.
  • Server-side rendering. Directives do not run during server rendering, because there is no DOM. If one affects the HTML that matters for SSR, it needs a getSSRProps hook (see server-side rendering).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which hook runs after the element has been inserted into the DOM, making it the place to call el.focus()?

    mounted runs after the element and its children are in the DOM, so focusing and measuring work there. In created and beforeMount the element is not inserted yet.
  2. 2. In v-demo:size.bold="count", what is binding.arg?

    The argument is the part after the colon, here size. bold is a modifier (binding.modifiers.bold is true) and count is the value.
  3. 3. Why does the v-click-outside directive remove its document listener in unmounted?

    A listener on document outlives the element. Without cleanup it keeps running, holds on to the element in memory and is added again with every new mount.
  4. 4. When is the function shorthand, app.directive("name", (el, binding) => { ... }), a good fit?

    The shorthand function is used for both mounted and updated. If you need other hooks, such as unmounted for cleanup, use the object form.

Summary

  • A custom directive is an object of optional hooks (created, beforeMount, mounted, beforeUpdate, updated, beforeUnmount, unmounted) that receive the real element.
  • binding carries value, oldValue, arg and modifiers.
  • In <script setup> a variable named vSomething is a directive; elsewhere use the directives option or app.directive().
  • v-focus and v-click-outside are typical: set up in mounted, undo in unmounted.
  • Use a directive only for direct DOM work; prefer components and composables for everything else.

Next: Plugins