<KeepAlive>

Caches toggled components to preserve their state instead of destroying them.

Since Vue 3.0 Spec ↗

Syntax

<KeepAlive :include :exclude :max>...</KeepAlive>

Parameters

NameTypeRequiredDescription
include string | RegExp | array No Only cache components whose name matches.
max number No Maximum number of cached instances.

Returns

component — Caches its single active child.

Examples

<script setup lang="ts">
import { ref, shallowRef } from 'vue';
import TabA from './TabA.vue';
import TabB from './TabB.vue';
const current = shallowRef(TabA);
</script>

<template>
  <button @click="current = TabA">A</button>
  <button @click="current = TabB">B</button>
  <KeepAlive :max="5">
    <component :is="current" />
  </KeepAlive>
</template>

Notes

Cached components are deactivated rather than unmounted, preserving state and DOM; they fire onActivated/onDeactivated instead of mount/unmount. Use include/exclude (matching component name) and max for an LRU cache. Commonly used with dynamic components and router views.