← Articles

Caching a component instance

“KeepAlive” is a Vue.js “built-in” component that caches a component instance when you switch between several components.

With this notation, you can use dynamic components:

<component :is="activeComponent"></component>

The “is” prop holds either the component name as a string, or the imported component itself. When “is” changes, the component changes. The active component that becomes inactive is unmounted, and any value held in its state is lost. When it becomes active again, a new instance of that component is created.

For example: Component A: holds a “count” Component B: holds a “message” input

When you switch from component A to component B, the value of the “count” is lost. When you switch from component B to component A, the value of the message is lost.

To avoid losing the state of the inactive component, you can use the “KeepAlive” component:

KeepAlive wrapping a dynamic component so that inactive components stay cached