How to Use v-once in Vue: Syntax, Example, and Tips
In Vue, use the
v-once directive on an element to render it only once and skip future updates. This is useful for static content that does not change, improving performance by avoiding unnecessary re-renders.Syntax
The v-once directive is added as an attribute to any HTML element or Vue component. It tells Vue to render the element and its children only once and then skip them in future updates.
Example parts:
v-once: The directive itself.- Placed inside the opening tag of an element or component.
vue
<div v-once>Static content here</div>
Output
<div>Static content here</div>
Example
This example shows a Vue component with a counter. The counter inside the v-once block will not update when the button is clicked, while the other counter updates normally.
vue
<template>
<div>
<p v-once>Counter with v-once: {{ count }}</p>
<p>Regular counter: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
</script>Output
<p>Counter with v-once: 0</p>
<p>Regular counter: 0</p>
<button>Increment</button>
Common Pitfalls
Common mistakes when using v-once include:
- Expecting reactive updates inside elements with
v-once. They will not update after the first render. - Using
v-onceon dynamic components or elements that need to change. - Placing
v-onceon parent elements unintentionally blocking updates of child elements.
Always use v-once only for truly static content.
vue
<!-- Wrong: v-once on parent blocks all updates -->
<div v-once>
<p>{{ dynamicText }}</p> <!-- This will never update -->
</div>
<!-- Right: v-once only on static part -->
<div>
<p v-once>Static text</p>
<p>{{ dynamicText }}</p> <!-- This updates normally -->
</div>Quick Reference
- Use: Add
v-onceto elements to render once and skip updates. - Best for: Static content that never changes.
- Not for: Dynamic or interactive content.
- Effect: Improves performance by reducing re-renders.
Key Takeaways
Use
v-once to render static content only once and skip future updates.Do not use
v-once on elements that need to react to data changes.Place
v-once carefully to avoid blocking updates on child elements.Using
v-once can improve performance by reducing unnecessary re-renders.