0
0
Vueframework~8 mins

Template refs for DOM access in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: Template refs for DOM access
MEDIUM IMPACT
Accessing DOM elements via template refs affects interaction responsiveness and can impact layout recalculations if used inefficiently.
Accessing and manipulating a DOM element in Vue
Vue
<template>
  <button @click="updateStyle">Click me</button>
  <div ref="box">Box</div>
</template>

<script setup>
import { ref } from 'vue'
const box = ref(null)
function updateStyle() {
  let newWidth = 100
  // Calculate final width once
  newWidth += 100
  box.value.style.width = `${newWidth}px`
}
</script>
Updates the DOM style only once, minimizing layout recalculations and improving responsiveness.
📈 Performance GainSingle reflow and repaint instead of 100, improving interaction speed.
Accessing and manipulating a DOM element in Vue
Vue
<template>
  <button @click="updateStyle">Click me</button>
  <div ref="box">Box</div>
</template>

<script setup>
import { ref } from 'vue'
const box = ref(null)
function updateStyle() {
  for (let i = 0; i < 100; i++) {
    box.value.style.width = `${100 + i}px`
  }
}
</script>
This code updates the DOM style 100 times in a loop, causing multiple layout recalculations and reflows.
📉 Performance CostTriggers 100 reflows and repaints, blocking interaction responsiveness.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Multiple style updates in loop via refMany writes100 reflowsHigh paint cost[X] Bad
Single style update via refOne write1 reflowLow paint cost[OK] Good
Rendering Pipeline
Template refs provide direct access to DOM nodes after Vue renders. Reading or writing styles via refs triggers style recalculation, layout, and paint stages.
Style Calculation
Layout
Paint
⚠️ BottleneckLayout stage is most expensive when DOM styles are changed repeatedly.
Core Web Vital Affected
INP
Accessing DOM elements via template refs affects interaction responsiveness and can impact layout recalculations if used inefficiently.
Optimization Tips
1Avoid multiple DOM writes in loops when using template refs.
2Batch style updates to trigger fewer layout recalculations.
3Use template refs only when necessary to minimize DOM access cost.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk when using template refs to update DOM styles inside a loop?
ATriggering many layout recalculations and reflows
BIncreasing JavaScript bundle size
CCausing network delays
DBlocking CSS parsing
DevTools: Performance
How to check: Record a performance profile while interacting with the component. Look for multiple Layout and Recalculate Style events triggered by the ref usage.
What to look for: Excessive layout recalculations and long scripting times indicate inefficient DOM access via refs.