Custom Directives
Custom directives provide a way to reuse logic that involves low-level DOM access. While composables are the primary way to reuse logic in Vue 3, directives are still useful when you need direct DOM manipulation.When to Use Directives
Use custom directives when you need to:- Directly manipulate DOM elements
- Apply reusable DOM-related behavior
- Integrate third-party DOM libraries
- Handle focus, animations, or other DOM-specific concerns
Directive Hooks
Based onruntime-core/src/directives.ts, custom directives are objects with lifecycle hooks:
Directive Binding Object
Thebinding argument provides:
Basic Example
Here’s a simple directive that focuses an input when mounted:Function Shorthand
When you only needmounted and updated hooks with the same behavior, use function syntax:
Real-World Example: v-show
Let’s examine Vue’s built-inv-show directive from runtime-dom/src/directives/vShow.ts:
Directive with Arguments and Modifiers
Directives can accept arguments and modifiers:Advanced Example: Click Outside
A common pattern for closing dropdowns/modals when clicking outside:Registering Directives
Local Registration
Register in a single component:Global Registration
Register globally usingapp.directive():
runtime-core/src/apiCreateApp.ts, the directive method signature is:
Directive with Reactive Data
Directives can work with reactive values:Deep Watching
Directives can opt into deep watching of objects:SSR Support
For server-side rendering, implementgetSSRProps: