Built-in Components
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
When a component is toggled inside
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
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:
- onActivated is also called on mount, and onDeactivated on unmount.
- Both hooks work for not only the root component cached by
, but also the descendant components in the cached tree.