Vue v-if Directive
🔀 Vue v-if Directive
It adds or removes elements from the DOM based on a condition.
What is Vue v-if Directive?
v-if renders an element only if the condition is true.
If isLogin is:
-
true→ element is shown -
false→ element is removed from the DOM
Basic Example
v-if with v-else
Used when you want two conditions.
📌 v-else must be immediately after v-if.
v-if with v-else-if
Used for multiple conditions.
Using v-if with <template>
When you need to conditionally render multiple elements.
📌 <template> does not appear in the DOM.
v-if vs v-show
| Feature | v-if |
v-show |
|---|---|---|
| DOM Handling | Adds/Removes element | Uses display: none |
| Initial Render | Slower | Faster |
| Toggle Cost | Lower | Higher |
| Use Case | Rare condition changes | Frequent toggling |
✔ Use v-if when condition changes rarely
✔ Use v-show when toggling often
v-if with Boolean Expressions
Common Mistakes ❌
❌ Using v-if and v-for together
✔ Correct way:
Key Points to Remember
-
v-ifremoves elements from DOM -
Works with:
-
v-else -
v-else-if
-
-
Use
<template>for multiple elements -
Better for conditional rendering logic
Conclusion
The v-if directive is essential for controlling what appears on the screen in a Vue app.
Understanding v-if helps you build clean, efficient, and optimized UIs.
