v-once is a directive in Vue.js that computes the value of the expression once during the initial render, and the value is then fixed. Even if the data changes, nodes with v-once will not update again. This is highly beneficial for performance optimization, especially when rendering large amounts of static content, as it reduces unnecessary virtual DOM reflows.
Compared to other common Vue directives such as v-if, v-for, v-model, and v-bind, the main difference with v-once is that it does not respond to changes in data. Other directives are typically used for data binding and view updates, meaning that when data changes, the view updates accordingly. For example:
v-ifdetermines whether to render an element based on the truthiness of the expression.v-foris used to render a data list.v-modelcreates a two-way binding between form inputs and application state.v-binddynamically binds one or more properties or passes property values to components.
Here is an example of using v-once:
html<div id="app"> <span v-once>Initial count: {{ initialCount }}</span> <button @click="increment">Click to increment</button> <span>Current count: {{ currentCount }}</span> </div> <script> new Vue({ el: '#app', data: { initialCount: 0, currentCount: 0 }, methods: { increment() { this.currentCount++; } } }); </script>
In this example, even if the value of initialCount is modified during the component's lifecycle, the <span> element with v-once will still display the value from the initial render. This shows that v-once only concerns one-time content rendering and does not participate in subsequent data update responses, which helps optimize rendering performance, especially in scenarios with a lot of static content.