QA
Beginner LevelVue JS

What is the difference between v-if and v-show and when should you use each?

❓ Interview Prompt: Explain conditional rendering in Vue, DOM element creation/destruction with v-if, and CSS display toggling with v-show.

Both directives toggle the visibility of an element, but have very different performance characteristics:

'v-if' (Real Conditional Rendering):

•
Lazy: If the condition is false on initial render, the element and its child components are never created or mounted in the DOM.
•
When toggled, Vue destroys and re-creates the DOM elements and component instances.
•
High toggle costs, but low initial render cost.

'v-show' (CSS Display Toggling):

•
Not Lazy: The element is always rendered and mounted in the DOM, regardless of initial condition.
•
Toggles visibility simply by switching inline CSS: 'display: none;' vs 'display: block;'.
•
Low toggle costs, but higher initial render cost.

When to Use:

•
Use 'v-show' if an element toggles frequently (like an accordion, modal, or dropdown menu).
•
Use 'v-if' if the condition rarely changes at runtime or depends on user authorization permissions.

Code Implementation Example

html
<!-- v-if: Element removed from DOM entirely when false -->
<div v-if="user.isAdmin">
  <AdminControlPanel /> <!-- Component unmounts/remounts on toggle -->
</div>
<div v-else>
  <p>Access Denied</p>
</div>

<!-- v-show: Always in DOM, hidden via inline style="display: none;" -->
<div v-show="isDropdownOpen" class="dropdown-menu">
  <ul>...</ul>
</div>
💡v-if DOM destruction vs v-show CSS display toggling.
🎯 Interview Key Takeaway

Use v-show for elements that toggle frequently. Use v-if for rare toggles or security-sensitive UI boundaries.

#v-if#v-show#Directives#Beginner
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?