v-memo
NOTE
This directive is available in Vue 3.2+ only.
v-memo memoizes a sub-tree of the template. It can be applied to both elements and components and accepts a fixed-length array of dependencies. On each render, Vue compares the current dependency values with those from the previous render. If all values are unchanged, Vue skips updating the entire subtree. It is important to specify the memoization array correctly, otherwise Vue may skip updates that should occur. Example:
<div v-memo="[valueA, valueB]">
...
</div>When the component re-renders, if both valueA and valueB remain the same, Vue skips all updates for this <div> and its children. In fact, Vue also skips creating new Virtual DOM nodes, reusing the previously memoized subtree instead.
v-memo with an empty dependency array (v-memo="[]") is functionally equivalent to v-once.
Usage with v-for
v-memo is provided solely for micro optimizations in performance-critical scenarios and should be rarely needed. The most common case where this may prove helpful is when rendering large v-for lists (where length > 1000):
<div
v-for="item in list"
:key="item.id"
v-memo="[item.id === selected]"
>
<p>ID: {{ item.id }} – selected: {{ item.id === selected }}</p>
<p>...more child nodes</p>
</div>When the component’s selected state changes, Vue would normally recreate a large number of VNodes, even though most items are unchanged. Here, v-memo tells Vue to update an item only when its selection state changes. All other items reuse their previous VNodes and completely skip diffing.
Note that item.id does not need to be included in the dependency array, as Vue automatically tracks it via the :key.
WARNING
When using v-memo with v-for, make sure both directives are used on the same element. v-memo does not work inside v-for.
v-memo can also be applied to components to manually prevent unwanted updates in certain edge cases where Vue’s default update checks become de-optimized. As always, it’s the developer’s responsibility to provide a correct dependency array to avoid skipping necessary updates.
