Imagine a dashboard where users apply filters, search for specific items, scroll through long lists, create custom views, and enter data into forms. Naturally, you want all of these interactions - the selections, inputs, and scroll positions - to be preserved exactly as the user left them, even if they navigate away and return later.
But how do you achieve this kind of seamless experience without rewriting large parts of your component or overhauling your app's structure?
The answer is simple: <keep-alive>.
What is <keep-alive>
<keep-alive> is a built-in Vue component that allows you to cache other components so that they don't get destroyed and recreated every time they're toggled or navigated away from.
Instead of reloading a component from scratch, Vue will keep it alive in memory, preserving its state, data, scroll position, and DOM structure.
When you wrap a dynamic component or <router-view> in <keep-alive>, Vue:
- Mounts the component only once.
- Keeps it in memory when it is no longer visible.
- Restores it instantly the next time it's needed.
When to Use <keep-alive>
- You're toggling between multiple views or tabs.
- A component is expensive to re-render.
- You want to keep user input or internal state when the view is hidden.
Basic Usage