#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 20 of 37easy

What is KeepAlive in Vue?

Caching component instances.

What You'll Learn

  • KeepAlive usage
  • Include/exclude patterns
  • Lifecycle hooks

Basic Usage

code.txtVUE
<template>
  <KeepAlive>
    <component :is="currentTab" />
  </KeepAlive>
</template>

Include/Exclude

code.txtVUE
<!-- Only cache these -->
<KeepAlive include="TabA,TabB">
  <component :is="currentTab" />
</KeepAlive>

<!-- Cache all except -->
<KeepAlive exclude="TabC">
  <component :is="currentTab" />
</KeepAlive>

<!-- Regex -->
<KeepAlive :include="/Tab[AB]/">
  <component :is="currentTab" />
</KeepAlive>

Max Cached Instances

code.txtVUE
<KeepAlive :max="10">
  <component :is="currentTab" />
</KeepAlive>

Special Lifecycle Hooks

code.jsJavaScript
import { onActivated, onDeactivated } from 'vue'

// Called when cached component is activated
onActivated(() => {
  console.log('Tab activated')
})

// Called when cached component is deactivated
onDeactivated(() => {
  console.log('Tab deactivated')
})