JAVASCRIPT
Dynamic Component Loading and Caching with Vue 3 `keep-alive`
Optimize performance and user experience in Vue 3 by dynamically loading components and caching their state using the `<keep-alive>` component, preventing re-renders.
// ComponentA.vue
<template>
<div>
<h3>Component A</h3>
<p>Current count: {{ count }}</p>
<button @click="count++">Increment A</button>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const count = ref(0);
onMounted(() => console.log('Component A Mounted!'));
</script>
// ComponentB.vue
<template>
<div>
<h3>Component B</h3>
<p>Current text: {{ text }}</p>
<input v-model="text" placeholder="Type something...">
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const text = ref('');
onMounted(() => console.log('Component B Mounted!'));
</script>
// App.vue
<template>
<div>
<h1>Dynamic Components with Keep Alive</h1>
<button @click="activeComponent = 'ComponentA'">Show Component A</button>
<button @click="activeComponent = 'ComponentB'">Show Component B</button>
<div class="component-wrapper">
<keep-alive>
<component :is="activeComponent"></component>
</keep-alive>
</div>
</div>
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
// Import components directly or define them as async components
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
const activeComponent = ref('ComponentA');
const components = {
ComponentA,
ComponentB
};
</script>
<style scoped>
.component-wrapper {
border: 1px solid #ccc;
padding: 20px;
margin-top: 20px;
min-height: 100px;
}
button {
margin-right: 10px;
}
</style>
How it works: The `<keep-alive>` built-in component in Vue 3 is used to conditionally cache dynamic components. When a component is wrapped by `<keep-alive>`, its state is preserved when it's deactivated (e.g., switched away from) and reused when it's reactivated, preventing unnecessary re-renders and re-initializations. This example demonstrates how switching between `ComponentA` and `ComponentB` retains their internal state (like the `count` or `text` input) when `<keep-alive>` is used, improving performance and user experience compared to re-mounting components from scratch each time.