YouTip LogoYouTip

Vue3 V Once

## Vue.js 3 `v-once` Directive The `v-once` directive in Vue 3 is a built-in performance optimization tool. It instructs Vue to render an element or component only once. On subsequent re-renders, the element/component and all of its children are treated as static content and skipped. --- ## Overview When Vue updates the DOM, it performs a virtual DOM diffing process to determine what has changed. By marking an element with `v-once`, you tell Vue's compiler and reactivity system that this node and its subtree will never change. This allows Vue to bypass dependency tracking and diffing for that specific subtree, boosting update performance. ### Specification * **Expression Expectation**: None (it does not accept any expression or value). * **Primary Function**: Renders the element or component exactly once, skipping all future updates. --- ## Use Cases & Examples ### 1. Static Content Optimization If you have sections of your page that display dynamic data initially (e.g., loaded from a database or configuration on mount) but should never change after the initial render, `v-once` is the ideal solution. Here is a practical example demonstrating how `v-once` preserves the initial state of an element even when the underlying reactive data changes. ```vue ``` ### 2. Optimizing Large Lists If you are rendering a large list of items using `v-for` and you know that the list items themselves will not change once rendered, you can combine `v-for` with `v-once` to significantly reduce memory usage and speed up updates: ```vue ``` --- ## Key Considerations While `v-once` is excellent for performance tuning, it should be used with caution: 1. **No Reactivity**: Any reactive data bindings (like `{{ message }}`) inside a `v-once` element will lose their reactivity after the initial render. Do not use it on elements that need to reflect state changes. 2. **Subtree Effect**: `v-once` affects the element it is declared on **and all of its nested children**. Ensure that no child elements require dynamic updates before applying `v-once` to a parent container. 3. **Alternative (`v-memo`)**: In Vue 3, if you need to conditionally skip updates based on specific reactive dependencies rather than skipping them permanently, consider using the [`v-memo`](https://vuejs.org/api/built-in-directives.html#v-memo) directive instead.
← Vue3 V ShowVue3 V Model β†’