0
0
Vueframework~5 mins

Keep-alive for expensive components in Vue

Choose your learning style9 modes available
Introduction

Keep-alive helps Vue remember a component's state and avoid reloading it every time you switch views. This saves time and makes your app feel faster.

When you have a component that takes a long time to load or fetch data.
When you want to keep user input or scroll position inside a component while switching between pages.
When switching tabs or views and you want to keep the previous tab's content ready instantly.
When you want to reduce unnecessary re-rendering of complex components.
When you want to improve user experience by keeping component state intact.
Syntax
Vue
<keep-alive>
  <component-to-cache />
</keep-alive>
Wrap the component you want to cache inside the tags.
Only works with dynamic or conditional components, not static ones.
Examples
This caches MyExpensiveComponent so it won't reload when toggled.
Vue
<keep-alive>
  <MyExpensiveComponent />
</keep-alive>
Only caches components named CompA and CompB when used dynamically.
Vue
<keep-alive include="CompA,CompB">
  <component :is="currentComp" />
</keep-alive>
Caches all components except CompC.
Vue
<keep-alive exclude="CompC">
  <component :is="currentComp" />
</keep-alive>
Sample Program

This example shows two components, A and B, each displaying the time they loaded. Using <keep-alive> keeps the component state, so switching back to a component shows the original load time instead of updating it.

Vue
<template>
  <div>
    <button @click="current = 'CompA'">Show A</button>
    <button @click="current = 'CompB'">Show B</button>

    <keep-alive>
      <component :is="current" />
    </keep-alive>
  </div>
</template>

<script setup>
import { ref, defineComponent } from 'vue'

const current = ref('CompA')

const CompA = defineComponent({
  name: 'CompA',
  data() {
    return { time: new Date().toLocaleTimeString() }
  },
  template: `<div>Component A - Loaded at: {{ time }}</div>`
})

const CompB = defineComponent({
  name: 'CompB',
  data() {
    return { time: new Date().toLocaleTimeString() }
  },
  template: `<div>Component B - Loaded at: {{ time }}</div>`
})
</script>
OutputSuccess
Important Notes

Keep-alive only caches components that are dynamically rendered using <component :is="..." /> or conditional rendering.

Cached components keep their state, including data and DOM, but you can control cache size with max prop.

Use include and exclude props to control which components to cache by name.

Summary

Keep-alive caches components to avoid reloading and improve speed.

Wrap dynamic components inside <keep-alive> to keep their state.

Use include and exclude to control caching behavior.