JAVASCRIPT
Dynamic Components and KeepAlive in Vue 3
Dynamically switch between Vue 3 components using `<component :is="..." />` and optimize performance by preserving component state with `<KeepAlive>`.
<template>
<div>
<h1>Dynamic Components Example</h1>
<button @click="currentTab = 'ComponentA'">Show Component A</button>
<button @click="currentTab = 'ComponentB'">Show Component B</button>
<div style="border: 1px solid #ccc; padding: 15px; margin-top: 20px;">
<!-- KeepAlive caches inactive component instances -->
<KeepAlive>
<component :is="currentTabComponent"></component>
</KeepAlive>
</div>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
const currentTab = ref('ComponentA');
const currentTabComponent = computed(() => {
switch (currentTab.value) {
case 'ComponentA':
return ComponentA;
case 'ComponentB':
return ComponentB;
default:
return ComponentA;
}
});
</script>
<!-- ComponentA.vue -->
<template>
<div>
<h2>Component A</h2>
<p>This component has a counter: {{ count }}</p>
<button @click="count++">Increment A</button>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const count = ref(0);
onMounted(() => console.log('Component A mounted'));
onUnmounted(() => console.log('Component A unmounted'));
</script>
<!-- ComponentB.vue -->
<template>
<div>
<h2>Component B</h2>
<p>This component has an input:</p>
<input type="text" v-model="textInput" placeholder="Type something...">
<p>Input value: {{ textInput }}</p>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const textInput = ref('');
onMounted(() => console.log('Component B mounted'));
onUnmounted(() => console.log('Component B unmounted'));
</script>
How it works: This code demonstrates how to render dynamic components in Vue 3 using the `<component :is="..." />` element. The `currentTabComponent` computed property resolves to the actual component instance based on `currentTab`'s value. Crucially, the `<KeepAlive>` wrapper ensures that inactive component instances (like `ComponentA` when `ComponentB` is active) are not destroyed but kept in memory. This preserves their state (e.g., `ComponentA`'s counter or `ComponentB`'s input value) and avoids re-rendering from scratch when switched back to, improving user experience and performance.