JAVASCRIPT
Managing Dynamic Components with `keep-alive` in Vue 3
Learn to render dynamic components in Vue 3 using `<component :is='...' />` and optimize performance by preserving their state and preventing re-rendering with `<keep-alive>`.
<!-- DynamicComponentHandler.vue -->
<template>
<div>
<button @click="activeComponent = components.ComponentA">Show Component A</button>
<button @click="activeComponent = components.ComponentB">Show Component B</button>
<div style="border: 1px solid #ccc; padding: 10px; margin-top: 20px;">
<keep-alive>
<component :is="activeComponent"></component>
</keep-alive>
</div>
</div>
</template>
<script setup>
import { ref, markRaw } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
const components = {
ComponentA: markRaw(ComponentA),
ComponentB: markRaw(ComponentB),
};
const activeComponent = ref(components.ComponentA);
</script>
<!-- ComponentA.vue -->
<template>
<div>
<h3>Component A</h3>
<input type="text" v-model="message" placeholder="Type something..." />
<p>Message: {{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('Hello from A');
console.log('ComponentA created/re-activated'); // For demonstration
</script>
<!-- ComponentB.vue -->
<template>
<div>
<h3>Component B</h3>
<p>This is Component B.</p>
</div>
</template>
<script setup>
console.log('ComponentB created/re-activated'); // For demonstration
</script>
How it works: Vue 3's `<component :is="...">` allows rendering components dynamically based on a variable. Wrapping it with `<keep-alive>` prevents inactive components from being unmounted, preserving their state and avoiding expensive re-renders when they are switched back into view. The `markRaw` function is used for imported component definitions to prevent them from becoming reactive, which is often a good practice for dynamic component references to optimize performance and avoid unnecessary overhead.