Vue 36: Custom Directives
easy⏱ 5 mincoursevue
Lifecycle hooks with raw DOM access
A custom directive is an object with lifecycle hooks — created, mounted, updated, unmounted, etc. — that receive the actual DOM element plus a binding object describing the value, argument, and modifiers passed to it in the template. It's the escape hatch for the rare cases a declarative template binding can't express, like measuring an element's size or wiring up a raw event listener.
<!-- main.js -->
app.directive('highlight', {
mounted(el, binding) {
el.style.background = binding.value;
},
updated(el, binding) {
el.style.background = binding.value;
},
});
<!-- anywhere in a template -->
<div v-highlight="'#42b883'">Styled via directive</div>
Global vs local registration
app.directive('name', {...}) registers a directive globally for the whole app, mirroring app.component. For a directive only one component needs, add a directives: { name: {...} } option to that component instead — same hook shape, just scoped locally.