0Pricing
Vue Academy · Lesson

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

  1. v-model: Two-Way Binding Internals
  2. v-on Event Modifiers
  3. v-bind Dynamic and Multiple Bindings
  4. Writing Custom Directives
← Back to Vue Academy