0
0
Vueframework~8 mins

v-if directive behavior in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: v-if directive behavior
MEDIUM IMPACT
Controls whether elements are added or removed from the DOM, impacting rendering and layout recalculations.
Conditionally showing or hiding UI elements
Vue
<template>
  <div v-show="showDetails">
    <p>Details here</p>
  </div>
</template>
Keeps element in DOM and only toggles visibility, avoiding reflows caused by DOM changes.
📈 Performance GainSingle paint update without reflow; smoother toggling.
Conditionally showing or hiding UI elements
Vue
<template>
  <div v-if="showDetails">
    <p>Details here</p>
  </div>
</template>
Each toggle adds or removes the element from the DOM, triggering layout recalculations and reflows.
📉 Performance CostTriggers 1 reflow per toggle; frequent toggling causes layout thrashing.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
v-if togglingAdd/remove nodes1 reflow per toggleMedium paint cost[X] Bad for frequent toggling
v-show togglingNo DOM changesNo reflowsLow paint cost[OK] Good for frequent toggling
Rendering Pipeline
When v-if condition changes, Vue adds or removes nodes from the DOM, triggering Style Calculation, Layout, and Paint stages.
Style Calculation
Layout
Paint
⚠️ BottleneckLayout stage is most expensive due to DOM changes causing reflows.
Core Web Vital Affected
LCP
Controls whether elements are added or removed from the DOM, impacting rendering and layout recalculations.
Optimization Tips
1Avoid frequent toggling of v-if to reduce layout recalculations.
2Use v-show to toggle visibility without removing elements from the DOM.
3Monitor Layout events in DevTools to detect costly DOM changes.
Performance Quiz - 3 Questions
Test your performance knowledge
What happens when a v-if condition toggles from false to true?
AThe element is hidden using CSS visibility.
BThe element remains in the DOM but is not visible.
CThe element is added to the DOM, triggering layout recalculation.
DNo DOM changes occur.
DevTools: Performance
How to check: Record a performance profile while toggling the v-if condition; look for Layout and Recalculate Style events.
What to look for: Frequent Layout events indicate costly DOM changes; fewer Layouts mean better performance.