How to Use v-once in Vue for Better Performance
Use Vue's
v-once directive to render an element or component only once, so Vue skips future updates for it. This improves performance by reducing unnecessary re-renders of static content.Syntax
The v-once directive is added as an attribute to an element or component in your template. It tells Vue to render that element only once and skip it in future updates.
Example parts:
v-once: The directive itself.- Placed inside the opening tag of an element or component.
vue
<div v-once>{{ message }}</div>Output
<div>Hello</div>
Example
This example shows a message rendered with v-once. Even if the message changes, the displayed text stays the same because Vue does not update it after the first render.
vue
<template>
<div>
<p v-once>{{ message }}</p>
<button @click="changeMessage">Change Message</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('Hello')
function changeMessage() {
message.value = 'Goodbye'
}
</script>Output
<p>Hello</p>
<button>Change Message</button>
Common Pitfalls
Common mistakes when using v-once include:
- Using it on dynamic content that needs to update, which causes stale data to show.
- Expecting reactive changes inside a
v-onceblock to update the UI. - Applying
v-oncetoo broadly, preventing needed reactivity.
Use v-once only for static content that never changes after initial render.
vue
<!-- Wrong: dynamic content won't update -->
<p v-once>{{ count }}</p>
<!-- Right: no v-once on dynamic content -->
<p>{{ count }}</p>Quick Reference
- Purpose: Render element once, skip future updates.
- Use case: Static content that never changes.
- Placement: Add
v-onceattribute to element/component. - Effect: Improves performance by reducing re-renders.
- Not for: Dynamic or reactive content.
Key Takeaways
Use
v-once to render static content only once for better performance.Do not use
v-once on content that needs to update reactively.Place
v-once directly on the element or component tag.It helps reduce unnecessary DOM updates and improves app speed.
Test carefully to avoid stale UI caused by improper
v-once use.