JAVASCRIPT
Render Dynamic Components with Asynchronous Loading in Vue 3
Learn to dynamically render components based on a variable and asynchronously load them for better performance using Vue 3's `<component :is>` and `defineAsyncComponent`.
// src/components/ComponentA.vue
<template>
<div class="component-a">
<h3>Component A</h3>
<p>This is content from Component A.</p>
</div>
</template>
// src/components/ComponentB.vue
<template>
<div class="component-b">
<h3>Component B</h3>
<p>This is content from Component B.</p>
</div>
</template>
// src/App.vue
<script setup>
import { ref, defineAsyncComponent } from 'vue';
// Synchronous component import
import ComponentA from './components/ComponentA.vue';
// Asynchronous component import using defineAsyncComponent
const ComponentB = defineAsyncComponent(() =>
import('./components/ComponentB.vue')
);
const currentComponent = ref('ComponentA'); // 'ComponentA' or 'ComponentB'
const componentsMap = {
ComponentA: ComponentA,
ComponentB: ComponentB
};
const selectComponent = (componentName) => {
currentComponent.value = componentName;
};
</script>
<template>
<div>
<h1>Dynamic & Async Components</h1>
<button @click="selectComponent('ComponentA')">Load Component A</button>
<button @click="selectComponent('ComponentB')">Load Component B (Async)</button>
<div class="component-container">
<component :is="componentsMap[currentComponent]"></component>
</div>
</div>
</template>
<style scoped>
.component-container {
margin-top: 20px;
padding: 15px;
border: 1px dashed #ccc;
min-height: 100px;
}
.component-a { color: blue; }
.component-b { color: green; }
</style>
How it works: This snippet demonstrates how to render components dynamically using Vue 3's `<component :is>` feature, where the `is` prop determines which component to render. It also shows how to asynchronously load components using `defineAsyncComponent`. Asynchronous loading improves initial page load performance by deferring the loading of components until they are actually needed, suitable for less frequently accessed parts of an application.