KeepAlive & Suspense
Preserve component state across dynamic switches with KeepAlive, and coordinate async loading states with Suspense.
The Problem KeepAlive Solves
By default, switching away from a component (via v-if, <component :is>, or a route change) fully destroys it — any local state, scroll position, or form input is lost. For components like tabs, where switching back and forth should feel instant and preserve exactly where the user left off, this is unwanted.
Using KeepAlive
Wrapping a dynamic component in <KeepAlive> caches its instance in memory instead of destroying it, so switching back restores it exactly as it was left.
<template> <KeepAlive> <component :is="currentTab" /> </KeepAlive></template><!-- With Vue Router --><template> <RouterView v-slot="{ Component }"> <KeepAlive> <component :is="Component" /> </KeepAlive> </RouterView></template><KeepAlive :include="['HomeTab', 'ProfileTab']"> limits caching to specific named components, useful when you only want some routes/tabs cached, not all of them.
Activated and Deactivated Hooks
A kept-alive component gets two extra lifecycle hooks — onActivated and onDeactivated — that fire each time it's shown or hidden, instead of the usual mount/unmount.
<script setup>import { onActivated, onDeactivated } from 'vue';
onActivated(() => { console.log('Tab shown again — resume polling, etc.');});
onDeactivated(() => { console.log('Tab hidden — pause anything expensive.');});</script>Suspense for Async Components
<Suspense>, seen briefly in the dynamic components lesson, coordinates a fallback UI while an async component (or any component with a top-level await in <script setup>) is still resolving.
<template> <Suspense> <template #default> <AsyncDashboard /> </template> <template #fallback> <p>Loading dashboard…</p> </template> </Suspense></template>FAQs
Yes — it caches whatever single component is toggled inside it, regardless of the specific mechanism switching it.
It's available and usable, though the Vue team has described it as an experimental feature — check current documentation for its exact status before relying on it heavily in production.
Summary
KeepAlive preserves component instances across switches, and Suspense coordinates loading states for async components. With data, forms, and error handling covered, the next section moves into production concerns — starting with TypeScript.