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
1️⃣ v-text
Sets the text content of an element.
Same as:
2️⃣ v-html
Renders raw HTML inside an element.
⚠️ Use carefully (can cause XSS attacks).
3️⃣ v-if
Conditionally renders elements.
4️⃣ v-else / v-else-if
Used with v-if.
5️⃣ v-show
Shows or hides elements using CSS (display: none).
📌 Difference:
-
v-if→ removes element from DOM -
v-show→ hides element only
6️⃣ v-for
Used for looping through arrays or objects.
7️⃣ v-bind
Binds HTML attributes dynamically.
Shortcut:
8️⃣ v-model
Creates two-way data binding (mostly used in forms).
9️⃣ v-on
Handles events like click, submit, etc.
Shortcut:
🔟 v-once
Renders element only once.
After initial render, it won’t update.
1️⃣1️⃣ 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.
