In Vue.js, the v-once
directive is used to render an element or component only once and prevent it from being re-rendered when the data it depends on changes. This directive is useful when you have static content that doesn't need to be updated dynamically.
Here's an example usage of v-once
:
s
<template>
<div>
<h1 v-once>{{ title }}</h1>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
title: 'Static Title',
message: 'Dynamic Message'
};
}
};
</script>
s
In this example, the <h1>
element is marked with the v-once
directive. It means that the title
value will be rendered only once and won't be updated if it changes. On the other hand, the <p>
element is not marked with v-once
, so the message
value will be updated if it changes.
When the component is initially rendered, the <h1>
element will display "Static Title" and remain unchanged, even if the title
value in the data object is modified. However, the <p>
element will be updated whenever the message
value changes.
By using v-once
, you can optimize performance by preventing unnecessary re-renders of static content. It's particularly useful for elements or components that have large amounts of static content or where the content doesn't depend on reactive data.
It's important to note that v-once
is not a two-way binding directive like v-model
. It only affects the initial rendering of the element or component and doesn't establish any reactivity between the rendered content and the data.
No comments:
Post a Comment