Directive Hooks in Vue: What They Are and How They Work
directive hooks are special functions that run at different stages of a custom directive's lifecycle, such as when it is created, updated, or removed. They let you control how the directive behaves on an element during these stages.How It Works
Directive hooks in Vue act like checkpoints during the life of a custom directive attached to an element. Imagine you have a helper that decorates a room. The hooks are like moments when the helper arrives, changes decorations, or cleans up before leaving.
Vue provides several hooks: created runs when the directive is first attached, beforeMount just before the element is added to the page, mounted after it appears, beforeUpdate and updated when the element or data changes, and unmounted when the directive is removed. Each hook lets you run code to control the element's behavior at that time.
This system helps you add custom behavior to elements in a clean, organized way, reacting to changes and cleaning up when needed.
Example
This example shows a custom directive that changes the background color of an element when it is mounted and logs messages during updates and removal.
import { createApp } from 'vue'; const app = createApp({ template: `<div v-color-directive="color">Hello Vue Directive!</div>`, data() { return { color: 'lightblue' }; } }); app.directive('color-directive', { created(el, binding) { console.log('Directive created with color:', binding.value); }, mounted(el, binding) { el.style.backgroundColor = binding.value; console.log('Directive mounted, background set'); }, updated(el, binding) { el.style.backgroundColor = binding.value; console.log('Directive updated, background changed'); }, unmounted(el) { console.log('Directive unmounted, cleanup if needed'); } }); app.mount('#app');
When to Use
Use directive hooks when you want to add custom behavior directly to DOM elements that Vue templates don't cover easily. For example:
- Manipulating element styles or attributes dynamically.
- Integrating third-party libraries that need direct DOM access.
- Adding event listeners or animations that depend on element lifecycle.
- Cleaning up resources when elements are removed.
They are perfect when you want reusable, low-level control over elements without mixing logic into components.
Key Points
- Directive hooks run at specific lifecycle stages of a custom directive.
- Common hooks include
created,mounted,updated, andunmounted. - They allow direct DOM manipulation and cleanup.
- Useful for adding reusable behaviors to elements.