JAVASCRIPT
Optimizing Component Rendering with Dynamic Components and KeepAlive
Learn to dynamically switch between Vue 3 components while preserving their state using <component :is="..."> and the <KeepAlive> wrapper for improved performance and UX.
<template>
<div class="dynamic-component-example">
<button @click="activeComponent = 'ComponentA'">Show A</button>
<button @click="activeComponent = 'ComponentB'">Show B</button>
<KeepAlive>
<component :is="activeComponent"></component>
</KeepAlive>
</div>
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
const ComponentA = defineAsyncComponent(() => import('./ComponentA.vue'));
const ComponentB = defineAsyncComponent(() => import('./ComponentB.vue'));
const activeComponent = ref('ComponentA');
</script>
<style scoped>
.dynamic-component-example button {
margin-right: 10px;
padding: 8px 15px;
cursor: pointer;
}
.dynamic-component-example div {
border: 1px solid #eee;
padding: 20px;
margin-top: 20px;
}
</style>
<!-- ComponentA.vue -->
<template>
<div>
<h3>Component A</h3>
<input type="text" v-model="message" placeholder="Type something in A">
<p>Message: {{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('Hello from A');
</script>
<!-- ComponentB.vue -->
<template>
<div>
<h3>Component B</h3>
<input type="number" v-model="count" placeholder="Enter a number in B">
<p>Count: {{ count }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
</script>
How it works: This snippet demonstrates how to render components dynamically using Vue 3's <component :is="..."> element. The <KeepAlive> wrapper is crucial here; it ensures that inactive dynamic components are cached instead of being unmounted. This preserves their state and avoids re-rendering, significantly improving performance and user experience when switching between components, such as tabs or different views. `defineAsyncComponent` is also used for lazy loading the components, further enhancing initial load performance.