Writing Custom Directives
app.directive(), mounted/updated/unmounted hooks, directive arguments and modifiers.
When Components Are Not Enough
Most reuse in Vue happens through components and composables. But some logic targets the raw DOM — autofocusing an input, integrating a non-Vue library, or measuring an element. Custom directives are built for exactly this.
A Minimal Directive
Register a directive on the app with app.directive. The mounted hook receives the element, so this directive focuses an input when it appears.
const app = createApp(App)
app.directive('focus', {
mounted(el) { el.focus() }
})All lessons in this course
- v-model: Two-Way Binding Internals
- v-on Event Modifiers
- v-bind Dynamic and Multiple Bindings
- Writing Custom Directives