·
1 min read

Vue Tip: Cache Component Instances With the KeepAlive Component

Vue Tip: Cache Component Instances With the KeepAlive Component Image

<KeepAlive> is a built-in Vue component that allows you to conditionally cache component instances when dynamically switching between multiple components.

Info

If you are not familiar with the concept of dynamic concepts, you should read the Dynamic Components documentation first.

Example

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.

App.vue
<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>

Interactive Demo

Try it yourself in the following demo:

Demo Without KeepAlive

Choose component

Component: A, count is 0

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.

App.vue
<template> <KeepAlive> <component :is="current"/> </KeepAlive> </template>

Let's see how it works in the following demo:

Demo With KeepAlive

Choose component

Component: A, count is 0

Now, when you switch between the components, the instances are cached, and the state of each component is preserved.

Additional Features

<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:

App.vue
<template> <KeepAlive include="ComponentA"> <component :is="current" /> </KeepAlive> </template>

Try it yourself in the following demo:

Demo With KeepAlive only for ComponentA

Choose component

Component: A, count is 0

For more information about the <KeepAlive> component, you can refer to the official documentation: KeepAlive Component.

StackBlitz

The following StackBlitz projects contains the source code for the examples shown in this article:

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.