Vue3 v-memo Directive

Vue3 内置指令Vue3 Built-in Directives


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>

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>

Difference between v-memo and v-once

DirectiveEffectApplicable Scenario
v-onceNever updateContent is completely static, no updates needed
v-memoNo update when dependencies remain unchangedContent only needs updating when specific dependencies change

Vue3 内置指令Vue3 Built-in Directives

Other Extensions