KeepAlive
<KeepAlive>
is a built-in component that allows us to conditionally cache component instances when dynamically switching between multiple components.
Basic Usage
In the Component Basics chapter, we introduced the syntax for Dynamic Components, using the <component>
special element:
<component :is="activeComponent" />
By default, an active component instance will be unmounted when switched away from. This will cause any changed state it holds to be lost.
In the example below, we have two stateful components - A contains a counter, while B contains a message synced with an input via v-model
. Try update the state of one of them, switch away, and then switch back to it:
Current component: A
count: 0You'll notice that when switched back, the previous changed state would have been reset.
Creating fresh component instance on switch is normally useful behavior, but in this case, we'd really like the two component instances to be preserved even when they are inactive. To solve this problem, we can wrap our dynamic component with the <KeepAlive>
built-in component:
<!-- Inactive components will be cached! -->
<KeepAlive>
<component :is="activeComponent" />
</KeepAlive>
Now, the state will be persisted across component switches:
Current component: A
count: 0TIP
When used in DOM templates, it should be referenced as <keep-alive>
.
Include / Exclude
By default, <KeepAlive>
will cache any component instance inside. We can customize this behavior via the include
and exclude
props. Both props can be a comma-delimited string, a RegExp
, or an array containing either types:
<!-- comma-delimited string -->
<KeepAlive include="a,b">
<component :is="view"></component>
</KeepAlive>
<!-- regex (use `v-bind`) -->
<KeepAlive :include="/a|b/">
<component :is="view"></component>
</KeepAlive>
<!-- Array (use `v-bind`) -->
<KeepAlive :include="['a', 'b']">
<component :is="view"></component>
</KeepAlive>
The match is checked against the component's name
option, so components that need to be conditionally cached by KeepAlive
must explicitly delcare a name
option.
Max Cached Instances
We can limit the maximum number of component instances that can be cached via the max
prop. When max
is specified, <KeepAlive>
behaves like an LRU cache: if the number of cached instances is about to exceed the specified max count, the least recently accessed cached instance will be destroyed to make room for the new one.
<KeepAlive :max="10">
<component :is="activeComponent" />
</KeepAlive>
Related