0
0
Vueframework~5 mins

Keep-alive for caching components in Vue

Choose your learning style9 modes available
Introduction

Keep-alive helps save the state of components so they don't reset when you switch views. It makes your app faster and smoother.

You want to keep form inputs filled when switching between pages.
You want to save scroll position in a list when going back and forth.
You want to avoid reloading data every time a component appears.
You want to improve user experience by keeping components alive in memory.
Syntax
Vue
<keep-alive>
  <component-to-cache />
</keep-alive>
Wrap the component you want to cache inside the tags.
Only works with dynamic or routed components.
Examples
This caches MyComponent so it keeps its state when hidden.
Vue
<keep-alive>
  <MyComponent />
</keep-alive>
This caches only components named MyComponent when used dynamically.
Vue
<keep-alive include="MyComponent">
  <component :is="currentView" />
</keep-alive>
This caches all components except OtherComponent.
Vue
<keep-alive exclude="OtherComponent">
  <component :is="currentView" />
</keep-alive>
Sample Program

This example shows two counters. Switching between them keeps their counts because they are wrapped in <keep-alive>. The counters do not reset when you switch views.

Vue
<template>
  <div>
    <button @click="currentView = 'CounterA'">Show Counter A</button>
    <button @click="currentView = 'CounterB'">Show Counter B</button>

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

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

const currentView = ref('CounterA')

const CounterA = {
  template: `<div>
    <p>Counter A: {{ count }}</p>
    <button @click="count++">Increment A</button>
  </div>`,
  data() {
    return { count: 0 }
  }
}

const CounterB = {
  template: `<div>
    <p>Counter B: {{ count }}</p>
    <button @click="count++">Increment B</button>
  </div>`,
  data() {
    return { count: 0 }
  }
}

const views = { CounterA, CounterB }

// Register components globally or locally
defineExpose({ views })
</script>
OutputSuccess
Important Notes

Keep-alive only caches components that are currently rendered dynamically or via routing.

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

Cached components keep their state and DOM, improving performance and user experience.

Summary

Keep-alive caches components to keep their state when switching views.

Wrap dynamic or routed components inside <keep-alive> tags.

Use it to improve speed and keep user input or scroll positions.