Vue3 Fundamentals · Built-in Components

Cache a component with KeepAlive

Caching component instances with KeepAlive

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.

App.vue
<script setup>
import { h, ref } from 'vue';

const show = ref(true);

const Counter = {
  setup() {
    const count = ref(0);
    return () =>
      h('button', { 'data-test': 'count', onClick: () => (count.value += 1) }, count.value);
  },
};
</script>

<template>
  <Counter v-if="show" />
  <button data-test="toggle" @click="show = !show">Toggle</button>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.