Michael Hoffmann
@mokkapps

<KeepAlive> is a built-in Vue component that allows you to conditionally cache component instances when dynamically switching between multiple components.
Let's take a look at a simple example to understand how <KeepAlive> works. We have two components, ComponentA and ComponentB, and we want to cache the instances of these components when switching between them.
<script setup>
import { shallowRef } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
const current = shallowRef(ComponentA);
</script>
<template>
<div>
<label
><input type="radio" v-model="current" :value="ComponentA" /> A</label
>
<label
><input type="radio" v-model="current" :value="ComponentB" /> B</label
>
</div>
<component :is="current"></component>
</template>
Try it yourself in the following demo:
If you switch between the components using the radio buttons, you will notice that the component instances are destroyed and recreated every time you switch between them. Thus, the state of each component is lost.
If you want to cache the instances of the components, you can wrap the <component> element with the <KeepAlive> component.
<template>
<KeepAlive>
<component :is="current"/>
</KeepAlive>
</template>
Let's see how it works in the following demo:
Now, when you switch between the components, the instances are cached, and the state of each component is preserved.
<KeepAlive> provides additional features to control the caching behavior of the components. You can use the include and exclude props to specify which components should be cached or excluded from caching.
Let's say you want to cache only the ComponentA instances. You can use the include prop to specify the name of the component:
<template>
<KeepAlive include="ComponentA">
<component :is="current" />
</KeepAlive>
</template>
Try it yourself in the following demo:
For more information about the <KeepAlive> component, you can refer to the official documentation: KeepAlive Component.
The following StackBlitz projects contains the source code for the examples shown in this article:
If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :
Vue Tip: Simple Routing Without Using External Libraries
Nuxt Tip: Change Status Code of the Response
