JAVASCRIPT
Vue 3 Dynamic Components with Asynchronous Loading
Implement dynamic components in Vue 3 using the `<component :is="...">` syntax, coupled with asynchronous loading for improved performance and code splitting.
// components/ComponentA.vue
<template>
<div style="border: 1px solid red; padding: 10px;">
<h3>Component A</h3>
<p>Content of Component A. (Loaded asynchronously)</p>
</div>
</template>
// components/ComponentB.vue
<template>
<div style="border: 1px solid blue; padding: 10px;">
<h3>Component B</h3>
<p>Content of Component B. (Loaded asynchronously)</p>
</div>
</template>
// App.vue
<template>
<div>
<h1>Dynamic Components</h1>
<button @click="currentComponent = 'ComponentA'">Show A</button>
<button @click="currentComponent = 'ComponentB'">Show B</button>
<div style="margin-top: 20px;">
<KeepAlive>
<component :is="currentComponent" />
</KeepAlive>
</div>
</div>
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
const currentComponent = ref('ComponentA');
// Asynchronously load components
const ComponentA = defineAsyncComponent(() =>
import('./components/ComponentA.vue')
);
const ComponentB = defineAsyncComponent(() =>
import('./components/ComponentB.vue')
);
// Make sure to register them if not using a build system that auto-registers
// or if you want to use them directly via their variable names in the template
// You can also import them directly if async loading is not needed for all.
</script>
How it works: This snippet demonstrates how to dynamically render different components using Vue's special `<component>` element and the `:is` prop. The `defineAsyncComponent` utility is used to lazy-load components, meaning they are only fetched from the server when they are actually needed. This significantly improves initial page load performance by enabling code splitting. The `KeepAlive` wrapper ensures that once an async component is loaded and rendered, it remains cached in memory, preserving its state when switched away and back, avoiding re-fetching and re-rendering.