Beginner LevelVue JS
How does <KeepAlive> cache dynamic component state between tab switching?
❓ Interview Prompt: Explain <KeepAlive>, caching dynamic component instances (<component :is="...">), preserving form state, and include/exclude props.
By default, when switching between dynamic components using '<component :is="activeTab" />', Vue destroys the unmounted component and creates the new component from scratch.
'<KeepAlive>':
Wrapping dynamic components in '<KeepAlive>' instructs Vue to cache unmounted component instances in memory instead of destroying them:
•
Preserves user input form state and scroll positions when switching tabs.
•
Supports 'include' and 'exclude' props to selectively target specific components.
Code Implementation Example
html
<script setup>
import { ref } from 'vue';
import UserProfile from './UserProfile.vue';
import UserSettings from './UserSettings.vue';
const currentTab = ref(UserProfile);
</script>
<template>
<!-- Cache unmounted tab component instances in memory! -->
<KeepAlive include="UserProfile">
<component :is="currentTab" />
</KeepAlive>
</template>💡Caching dynamic component state across tab navigation using <KeepAlive>.
🎯 Interview Key Takeaway
<KeepAlive> caches unmounted component instances in memory, preserving state and scroll positions during tab navigation.
#KeepAlive#Caching#Dynamic Components#Beginner
Back to all Vue JS Questions→