keep-alive
keep-alive caches inactive components so they keep their state instead of being destroyed.
In this page:
Syntax
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
keep-alive
Wrap dynamic components or router views in keep-alive and Vue keeps their instances in memory when switched away, preserving data and scroll. include and exclude choose which to cache and max limits the cache.
Cached components get activated and deactivated hooks.
Note:
Use the max attribute to bound memory use.
Example: keep-alive
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<button @click="tab = tab === 'note-a' ? 'note-b' : 'note-a'">Switch</button>
<keep-alive><component :is="tab"></component></keep-alive>
</div>
<script>
const app = Vue.createApp({ data() { return { tab: "note-a" }; } });
app.component("note-a", { data() { return { text: "draft" }; }, template: "<p>A: {{ text }} <button @click=\"text += '!'\">edit</button></p>" });
app.component("note-b", { template: "<p>B</p>" });
app.mount("#app");
(async () => {
document.querySelectorAll("button")[1].click(); await Vue.nextTick(); // edit A
document.querySelectorAll("button")[0].click(); await Vue.nextTick(); // to B
document.querySelectorAll("button")[0].click(); await Vue.nextTick(); // back to A
console.log("state kept after switching:", document.querySelector("p").textContent);
})();
</script>
</body>
</html>
<!-- Output:
Rendered: SwitchA: draft! edit
console: state kept after switching: A: draft! edit
-->
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Caching everything and leaking memory
- Expecting created to run again
- Forgetting activated hooks
Chapter Summary
- keep-alive caches instances
- State survives switching
- include, exclude, max control it
- activated and deactivated hooks
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: