Vue Tip: Cache Component Instances With the KeepAlive Component
<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.
Interactive Demo
Try it yourself in the following demo:
Demo Without KeepAlive
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.
Let's see how it works in the following demo:
Demo With KeepAlive
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:
Try it yourself in the following demo:
Demo With KeepAlive only for ComponentA
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:
Nuxt Tip: Change Status Code of the Response
`setResponseStatus` is a Nuxt composable to set the status code and (and optionally the status message) of the response.
Vue Tip: Simple Routing Without Using External Libraries
If you want to keep things simple and avoid adding extra dependencies, you can implement basic routing functionality in Vue.js without using external libraries like Vue Router.