← Back to all tutorials

Custom Directives

Create your own Vue directives — extend HTML with custom behaviors like auto-focus, click-outside, and color theming.

Custom Directives

Vue's built-in directives like v-if, v-for, and v-model cover most needs. But you can also create custom directives for reusable DOM manipulations.

Registering a Global Directive

// main.js
Vue.directive('rainbow', {
    bind(el) {
        el.style.color = '#' + Math.random().toString(16).slice(2, 8);
    }
});
<p v-rainbow>This text has a random color!</p>

Directive Hooks

HookWhen It Runs
bindWhen the directive is first bound to the element
insertedWhen the element is inserted into the DOM
updateWhen the containing component's VNode is updated
unbindWhen the directive is unbound from the element

Directive with a Value

Vue.directive('theme', {
    bind(el, binding) {
        if (binding.value === 'wide') {
            el.style.maxWidth = '1200px';
        } else {
            el.style.maxWidth = '560px';
        }
        if (binding.arg === 'column') {
            el.style.background = '#ddd';
            el.style.padding = '20px';
        }
    }
});
<div v-theme:column="'wide'">Wide column content</div>
<div v-theme="'narrow'">Narrow content</div>

Hook Arguments

ArgumentContains
elThe DOM element the directive is bound to
binding.valueThe value passed to the directive (v-dir="value")
binding.argThe argument after the colon (v-dir:arg)
binding.modifiersModifiers as an object (v-dir.mod)

Key Takeaways

  • Custom directives handle low-level DOM manipulation that does not fit into components
  • Register globally with Vue.directive(name, hooks)
  • bind runs once when attached; inserted when in the DOM; update on changes
  • Access the element with el, the value with binding.value, and arguments with binding.arg