Vue 3 Basic
What is the difference between v-if and v-show?
Core Difference
v-if |
v-show |
|
|---|---|---|
| Rendering | Completely removes/adds DOM when false | Toggles display: none when false |
| Initial render | Lazy (skips render when false) | Always renders |
| Toggle cost | High (destroys/recreates DOM and components) | Low (only CSS change) |
| Initial cost | Low (no render when false) | High (always renders) |
Supports v-else |
✅ Yes | ❌ No |
Works on <template> |
✅ Yes | ❌ No |
Example
<!-- v-if: DOM is fully removed/created -->
<div v-if="isLoggedIn">
Welcome back!
</div>
<div v-else>
Please log in
</div>
<!-- v-show: DOM always exists, only display is toggled -->
<div v-show="isLoading">
Loading...
</div>
Lifecycle Difference
<!-- v-if = false → component destroyed, onUnmounted called -->
<!-- v-if = true → component recreated, onMounted called -->
<MyComponent v-if="show" />
<!-- v-show = false → component NOT destroyed, lifecycle not re-run -->
<MyComponent v-show="show" />
When to Use Which?
| Scenario | Recommendation |
|---|---|
| Frequent toggling (dropdowns, tooltips) | v-show |
| Condition is false most of the time initially | v-if |
Need v-else |
v-if |
| Complex child components (avoid re-creation) | v-show |
| Security concern (element must not exist in DOM) | v-if |
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
