Optimizing Component Renders with v-once and VDOM
Describe how to use the v-once directive to statically render parts of the template once, reducing the load on the VDOM during updates.
<template>
<div>
<!-- Static content using v-once, will only be rendered a single time -->
<h1 v-once>Static Title</h1>
<p v-once>This paragraph will never change after initial render.</p>
<!-- Dynamic content which may re-render -->
<div>
{{ dynamicContent }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
dynamicContent: 'This content may change.'
};
},
methods: {
updateDynamicContent() {
// Method to update dynamic content
this.dynamicContent = 'Updated dynamic content!';
}
}
}
</script>
In this Vue component template, the 'v-once' directive is used to ensure that the <h1> and <p> are only rendered once and not updated by subsequent component re-renders. The 'dynamicContent' data property is reactive and will trigger updates to the connected part of the DOM when modified. The 'v-once' static content reduces the load on the Virtual DOM (VDOM) since these pieces won't require diffing on updates, contributing to better performance for the static sections.
<style>
h1 {
font-size: 24px;
color: #333;
}
p {
font-size: 16px;
color: #666;
}
div {
margin-top: 10px;
}
</style>
Simple CSS styles for the Vue component to define the appearance of the <h1> title, <p> paragraph, and <div> container. These styles are not directly related to Vue's 'v-once' directive but are included to style the content for better presentation.