How to Use Modifiers in Custom Directive in Vue
In Vue, you can access modifiers in a custom directive through the
binding.modifiers object inside the directive hooks. Modifiers are boolean flags that let you customize directive behavior by adding dot-syntax options like v-my-directive.modifier.Syntax
In a Vue custom directive, modifiers are accessed via binding.modifiers, which is an object containing keys for each modifier used. You define a directive and check these keys to change behavior.
- binding.modifiers: An object with modifier names as keys and
trueas values if present. - Usage in template: Add modifiers after the directive name with dots, e.g.
v-my-directive.mod1.mod2.
javascript
app.directive('my-directive', { mounted(el, binding) { if (binding.modifiers.mod1) { // Do something for mod1 } if (binding.modifiers.mod2) { // Do something for mod2 } } });
Example
This example shows a custom directive v-color that changes text color. It uses modifiers red and blue to set the color accordingly.
javascript
import { createApp } from 'vue'; const app = createApp({ template: ` <div> <p v-color.red>This text is red.</p> <p v-color.blue>This text is blue.</p> <p v-color>This text is black (default).</p> </div> ` }); app.directive('color', { mounted(el, binding) { if (binding.modifiers.red) { el.style.color = 'red'; } else if (binding.modifiers.blue) { el.style.color = 'blue'; } else { el.style.color = 'black'; } } }); app.mount('#app');
Output
Three paragraphs: first text in red, second in blue, third in black.
Common Pitfalls
Common mistakes when using modifiers in custom directives include:
- Forgetting that
binding.modifiersis an object, not a string. - Using modifiers without checking if they exist, which can cause unexpected behavior.
- Trying to pass values through modifiers (modifiers are boolean flags only).
Always check for the presence of a modifier key before acting.
javascript
/* Wrong way: treating modifiers as string */ app.directive('example', { mounted(el, binding) { // Incorrect: binding.modifiers is an object, not a string if (binding.modifiers === 'active') { el.style.fontWeight = 'bold'; } } }); /* Right way: check modifier key */ app.directive('example', { mounted(el, binding) { if (binding.modifiers.active) { el.style.fontWeight = 'bold'; } } });
Quick Reference
Modifiers in Vue custom directives:
- Access via
binding.modifiersas an object. - Modifiers are boolean flags, true if used.
- Use dot syntax in template:
v-directive.mod1.mod2. - Check modifiers in directive hooks to customize behavior.
Key Takeaways
Access modifiers in custom directives via binding.modifiers object.
Modifiers are boolean flags set by dot syntax after directive name.
Always check if a modifier exists before using it in your directive.
Modifiers cannot carry values; they only indicate presence or absence.
Use modifiers to add flexible, reusable behavior to your directives.