Built-in Components

is a built-in component that allows us to conditionally cache component instances when dynamically switching between multiple components. Caches dynamically toggled components wrapped inside.

When wrapped around a dynamic component,
<KeepAlive> caches the inactive component
instances without destroying them.

There can only be one active component instance
as the direct child of at any time.

When a component is toggled inside , its activated and deactivated lifecycle hooks will be invoked accordingly, providing an alternative to mounted and unmounted, which are not called. This applies to the direct child of as well as to all of its descendants.

Example

<KeepAlive>
  <component :is="view"></component>
</KeepAlive>

<KeepAlive>
  <comp-a v-if="a > 1"></comp-a>
  <comp-b v-else></comp-b>
</KeepAlive>

<Transition>
  <KeepAlive>
    <component :is="view"></component>
  </KeepAlive>
</Transition>

<!-- comma-delimited string -->
<KeepAlive include="a,b">
  <component :is="view"></component>
</KeepAlive>

<!-- regex (use `v-bind`) -->
<KeepAlive :include="/a|b/">
  <component :is="view"></component>
</KeepAlive>

<!-- Array (use `v-bind`) -->
<KeepAlive :include="['a', 'b']">
  <component :is="view"></component>
</KeepAlive>

<KeepAlive :max="10">
  <component :is="view"></component>
</KeepAlive>

Lifecycle of Cached Instance

When a component instance is removed from the DOM but is part of a component tree cached by , it goes into a deactivated state instead of being unmounted. When a component instance is inserted into the DOM as part of a cached tree, it is activated.

A kept-alive component can register lifecycle hooks for these two states using onActivated() and onDeactivated():

<script setup>
import { onActivated, onDeactivated } from 'vue'

onActivated(() => {
  // called on initial mount
  // and every time it is re-inserted from the cache
})

onDeactivated(() => {
  // called when removed from the DOM into the cache
  // and also when unmounted
})
</script>

Note that: