What is the difference between v-if and v-show?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Vue.js development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
Both v-if and v-show control element visibility, but they work differently: v-if: conditionally renders the element — it is literally added to or removed from the DOM based on the condition. When the condition is false, the element and its component children are completely destroyed (component lifecycle hooks fire). When it becomes true, they are recreated from scratch. It is a "real" conditional rendering: <ExpensiveComponent v-if="isActive" />. Pros: lower initial render cost (don't render elements that start as false); Cons: higher toggle cost (destroy/recreate). v-show: always renders the element but toggles the CSS display property between none and its original value. The element stays in the DOM; component lifecycle runs once. <ExpensiveComponent v-show="isActive" />. Pros: fast toggle (just a CSS change); Cons: always incurs the initial render cost. When to use which: use v-if when: the condition rarely changes, the element is expensive and shouldn't be rendered when not needed, or the element contains sensitive content. Use v-show when: you need to toggle frequently (tabs, accordion) and the initial render cost is acceptable. v-if + v-for: avoid using on the same element — v-if has higher priority in Vue 3 (v-for in Vue 2). Instead, wrap in a template or filter the array in a computed property.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Vue.js answers easy to follow.