What is <KeepAlive> in Vue?
Answer
<KeepAlive> is a built-in Vue component that caches (keeps alive) component instances when they are switched out of a dynamic component or route view, instead of destroying and recreating them. Usage: wrap dynamic component or RouterView: <KeepAlive><component :is="activeTab" /></KeepAlive>. Or with Vue Router: <RouterView v-slot="{ Component }"><KeepAlive><component :is="Component" /></KeepAlive></RouterView>. Effect: when a component is "kept alive," switching away doesn't unmount it — its state (scroll position, form data, timer state) is preserved. Switching back shows the same state. The component goes inactive (onDeactivated fires) and back to active (onActivated fires) instead of unmounted/mounted. include/exclude: selectively cache components: <KeepAlive include="UserList,ProductList"> (comma-separated component names), or RegExp, or array. max: limit the number of cached instances: <KeepAlive :max="10"> — when limit exceeded, the least recently used instance is destroyed. Use cases: tabbed interfaces (preserve tab content state), search results (go back without refetch), multi-step forms (preserve earlier step state while navigating). Cost: cached components consume memory — only keep-alive what provides clear UX benefit.
Previous
What is the Vue transition system?
Next
What is the defineProps and defineEmits in Vue 3 script setup?