Episode 34 of 44
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
| Hook | When It Runs |
|---|---|
bind | When the directive is first bound to the element |
inserted | When the element is inserted into the DOM |
update | When the containing component's VNode is updated |
unbind | When 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
| Argument | Contains |
|---|---|
el | The DOM element the directive is bound to |
binding.value | The value passed to the directive (v-dir="value") |
binding.arg | The argument after the colon (v-dir:arg) |
binding.modifiers | Modifiers 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) bindruns once when attached;insertedwhen in the DOM;updateon changes- Access the element with
el, the value withbinding.value, and arguments withbinding.arg