KeepAlive
Basic Usage
<!-- Inactive components will be cached! -->
<KeepAlive>
<component :is="activeComponent" />
</KeepAlive>
Include / Exclude
By default, <KeepAlive>
will cache any component instance inside. We can customize this behavior via the include
and exclude
props. Both props can be a comma-delimited string, a RegExp
, or an array containing either types
The match is checked against the component's name
option
<!-- comma-delimited string -->
<KeepAlive include="a,b">
<component :is="view" />
</KeepAlive>
<!-- regex (use `v-bind`) -->
<KeepAlive :include="/a|b/">
<component :is="view" />
</KeepAlive>
<!-- Array (use `v-bind`) -->
<KeepAlive :include="['a', 'b']">
<component :is="view" />
</KeepAlive>
Lifecycle of Cached Instance
- Both hooks work for not only the root component cached by
<KeepAlive>
, but also the descendant components in the cached tree
<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>