Custom Directives
Custom directives encapsulate low-level DOM behaviors. This lesson covers practical patterns, syntax, and mistakes to avoid.
Writing Vue Directives
Custom directives encapsulate low-level DOM behaviors.
Prefer components/composables first; directives for truly DOM-centric needs.
const vFocus = {
mounted: (el) => el.focus()
}
// usage: <input v-focus />
Auto-focus directive.
Hooks
created, beforeMount, mounted, updated, unmounted
- Handle loading and errors.
- Keep composables tested.
- Prefer TypeScript when you can.
- Measure before optimizing.
Custom Directives Cheatsheet
Quick reference for patterns covered in this lesson.
| Item | Example | Purpose |
| mounted | DOM ready | Common |
| updated | after patch | Care |
| arg | v-dir:arg | Config |
| value | binding.value | Data |
| modifiers | .foo | Flags |
| SSR | getSSRProps | Advanced |
When Not To
If you need state/template, use a component.
Common Mistakes
- Rebuilding components as directives.
- Forgetting unmount cleanup.
Key Takeaways
- Custom Directives shows up often in Vue apps.
- Practice with a demo.
- Prefer clear APIs.
- Read official docs for edge cases.
Pro Tip
Name directives with vXxx objects and register locally when possible.