Vue Directives

Vue Directives
They tell Vue how to behave with the DOM (HTML elements).
Example:
What are Vue Directives?
Vue directives are instructions written in HTML that control:
Rendering
Loops
Events
Data binding
User input handling
All directives start with v-.
Commonly Used
v-text
Sets the text content of an element.
Same as:
v-html
Renders raw HTML inside an element.
Use carefully (can cause XSS attacks).
v-if
Conditionally renders elements.
v-else / v-else-if
Used with v-if.
v-show
Shows or hides elements using CSS (display: none).
Difference:
v-if→ removes element from DOMv-show→ hides element only
v-for
Used for looping through arrays or objects.
v-bind
Binds HTML attributes dynamically.
Shortcut:
v-model
Creates two-way data binding (mostly used in forms).
v-on
Handles events like click, submit, etc.
Shortcut:
v-once
Renders element only once.
After initial render, it won’t update.
v-pre
Skips compilation for that element.
Custom Directives
It also allows creating custom directives.
Usage:
Summary Table
| Directive | Purpose |
|---|---|
v-if | Conditional rendering |
v-show | Toggle visibility |
v-for | Looping |
v-bind | Attribute binding |
v-model | Two-way binding |
v-on | Event handling |
v-html | Render HTML |
v-once | One-time render |
Conclusion
It make templates powerful, dynamic, and easy to read.
Mastering directives is essential before moving to components and composition API.
