Performance: Template refs for DOM access
Accessing DOM elements via template refs affects interaction responsiveness and can impact layout recalculations if used inefficiently.
<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>
<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>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple style updates in loop via ref | Many writes | 100 reflows | High paint cost | [X] Bad |
| Single style update via ref | One write | 1 reflow | Low paint cost | [OK] Good |
template refs in Vue?<script setup> syntax?const myRef = ref(null); to create a ref variable initialized to null.reactive is for objects, not refs. computed is for derived values. Using var is discouraged and 'element' is not a valid initial value for a ref to DOM.<template>
<input ref="inputRef" />
<button @click="focusInput">Focus</button>
</template>
<script setup>
import { ref } from 'vue';
const inputRef = ref(null);
function focusInput() {
console.log(inputRef.value.tagName);
inputRef.value.focus();
}
</script><template>
<div ref="box">Content</div>
</template>
<script setup>
import { ref } from 'vue';
const box = ref();
console.log(box.value.textContent);
</script>Pass the test and this pattern moves unknown