Cache a component with KeepAlive
Toggle a component away with v-if and Vue destroys it. Toggle it back and Vue
builds a fresh instance, so any state it held is gone. That is usually what you
want, but sometimes you want the component to remember where it left off.
<KeepAlive> caches the component it wraps. When the child leaves, Vue keeps
its instance instead of destroying it. When the child returns, Vue reuses that
instance, so its state is exactly as it was.
<template>
<KeepAlive>
<Counter v-if="show" />
</KeepAlive>
<button @click="show = !show">Toggle</button>
</template>
<KeepAlive> expects one component child, so it pairs with v-if or
<component :is>. A plain element is not cached — only a component has an
instance worth keeping.
The file already defines a small Counter child that holds a count. Wrap it in
<KeepAlive> so the count survives a trip away and back. The Test clicks the
counter, toggles it off, toggles it on, and checks the count is still there.
Without <KeepAlive> the fresh instance starts at zero, so the Test fails.
Challenge
The counter forgets its value every time it is hidden. Wrap the child in
<KeepAlive> so its state survives: export an App component from App.vue
that keeps the Counter instance alive across the toggle.
The Test clicks the counter to reach 1, toggles it away, toggles it back, and
expects the counter to still read 1. The starter renders the child without
<KeepAlive>, so the count resets and the Test fails.