How to use the v-once for optimization In Vue
The v-once directive ensures that the element or component it’s applied to is rendered only once during the initial render cycle. Subsequent updates to reactive data within that element or component will not trigger re-rendering.
Example: The below code implements the v-once directive to render the VueJS code.
<template>
<div style="text-align: center">
<h2>
The text below input field will
not change as it<br /> is rendered
using v-once directive.
</h2>
<input type="text" v-model="reply" />
<h3 v-once>{{ reply }}</h3>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const reply = ref("Reply");
return {
reply
};
}
};
</script>
Output:
Key Features of v-once:
- Renders the content only once, even if reactive data within it changes.
- Ideal for static content that never needs to update.
- Can be used with individual elements, components, or even sections wrapped with a container element.
Vue Render Optimization with v-once and v-memo
Rendering speed is crucial for a good user experience in modern apps. Out of all ways, one extremely easy way to optimize rendering is by only re-rendering what needs to be. While Vue re-renders components when their data changes this can lead to inefficiencies. v-once and v-memo directives offer a solution by allowing control over re-rendering, improving performance.
Table of Content
- How v-once and v-memo Optimize the Vue Render?
- Using the v-once for optimization
- Using the v-memo for optimization
Contact Us