Vue <KeepAlive> Component


Example

Using the built-in <KeepAlive> component to make the components keep the previously entered user inputs:

<KeepAlive>
  <component :is="activeComp"></component>
</KeepAlive>
Run Example »

See more examples below.


Definition and Usage

The built-in <KeepAlive> component is used around dynamic components to cache the components when they are not active, so that their state is kept.


Props

The <KeepAlive> component can be used together with different props so that we can specify which components that should be cached so that they keep their state.

Prop Description
none All components are cached so that their state is kept Run Example »
include Optional. Specify the names of the components that should keep their state Run Example »
exclude Optional. Specify the names of the components that should not keep their state Run Example »
max Optional. Specify the maximum number of components that should keep their state. If you specify to cache a maximum of 4 components, it will be the 4 components that were last visited that are cached Run Example »

The Lifecycle of Components Cached with <KeepAlive>

Components that are cached with the built-in <KeepAlive> component will switch between the activated and deactivated states when they are set, or not set, as the active dynamic component.

The activated() and deactivated() lifecycle hooks can be used to run code when such a cached component is set, or not set, as the active component.


More Examples

Example

Using the include prop to specify which components that will cache the values:

<KeepAlive include="CompOne,CompThree">
  <component :is="activeComp"></component>
</KeepAlive>
Run Example »

Example

Using the exclude prop to specify which components that will not cache the values:

<KeepAlive exclude="CompOne">
  <component :is="activeComp"></component>
</KeepAlive>
Run Example »

Example

Using the max prop to specify how many of the last visited components that will cache the values:

<KeepAlive :max="2">
  <component :is="activeComp"></component>
</KeepAlive>
Run Example »

Related Pages

Vue Tutorial: Dynamic Components

Vue Tutorial: The 'activated' and 'deactivated' Lifecycle Hooks


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.