← Back to Vue.js Course | Chapter 10: Best Practices | Lesson 5 of 6

keep-alive

keep-alive caches inactive components so they keep their state instead of being destroyed.

In this page:

  1. keep-alive
Syntax
markup
<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

markup
<!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
  1. Caching everything and leaking memory
  2. Expecting created to run again
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.