Vue3 v-memo Directive
v-memoThe directive is used to memoize the subtree of a template and decide whether to skip updates by specifying an array of dependency values.
Only available in Vue 3.2+.
Basic Description
v-memoThe directive allows you to memoize part of a template. It expects a fixed-length array of dependency values. If every value in the array is the same as the last render, the entire subtree update will be skipped.
- Expected Type: any[]
- Effect: Memoize the template subtree, and decide whether to skip updates by specifying an array of dependency values.
Basic Syntax
Example
<!-- When both valueA and valueB remain unchanged, skip update -->
<div v-memo="[valueA, valueB]">
<!-- Content -->
</div>
<!-- Empty array is equivalent to v-once -->
<div v-memo="[]">
Never update
</div>
<div v-memo="[valueA, valueB]">
<!-- Content -->
</div>
<!-- Empty array is equivalent to v-once -->
<div v-memo="[]">
Never update
</div>
Use Cases
1. Long List Optimization
v-memo is especially useful when handling large lists, allowing you to skip list items that do not need updating:
Example
<template>
<div class="list">
<div
v-for="item in items"
:key="item.id"
v-memo="[item.isSelected, item.isExpanded]"
class="item"
>
<div class="header">{{ item.title }}</div>
<div v-if="item.isExpanded" class="content">
{{ item.description }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, title: 'Title 1', description: 'Description 1', isSelected: true, isExpanded: false },
{ id: 2, title: 'Title 2', description: 'Description 2', isSelected: false, isExpanded: true }
]
}
}
}
</script>
<div class="list">
<div
v-for="item in items"
:key="item.id"
v-memo="[item.isSelected, item.isExpanded]"
class="item"
>
<div class="header">{{ item.title }}</div>
<div v-if="item.isExpanded" class="content">
{{ item.description }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, title: 'Title 1', description: 'Description 1', isSelected: true, isExpanded: false },
{ id: 2, title: 'Title 2', description: 'Description 2', isSelected: false, isExpanded: true }
]
}
}
}
</script>
Difference between v-memo and v-once
| Directive | Effect | Applicable Scenario |
|---|---|---|
| v-once | Never update | Content is completely static, no updates needed |
| v-memo | No update when dependencies remain unchanged | Content only needs updating when specific dependencies change |
Other Extensions
Vue3 Built-in Directives