JAVASCRIPT
Dynamic and Asynchronous Components in Vue 3
Learn how to dynamically render components based on data using Vue's `is` attribute and improve performance with asynchronous components, loading them only when needed.
<template>
<div>
<h1>Dynamic & Async Components</h1>
<button @click="loadComponent('ComponentA')">Load Component A</button>
<button @click="loadComponent('ComponentB')">Load Component B</button>
<button @click="loadComponent('AsyncComponentC')">Load Async Component C</button>
<div class="component-container">
<component :is="currentComponent"></component>
</div>
</div>
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
// Define regular components
const ComponentA = {
template: '<div style="background-color: #e0ffe0; padding: 10px;">Component A Content</div>'
};
const ComponentB = {
template: '<div style="background-color: #e0e0ff; padding: 10px;">Component B Content</div>'
};
// Define an asynchronous component
// This component will only be loaded from its file when it's rendered for the first time.
const AsyncComponentC = defineAsyncComponent(() =>
import('./AsyncComponentC.vue') // Assuming AsyncComponentC.vue exists
);
const currentComponent = ref(null);
const loadComponent = (componentName) => {
if (componentName === 'ComponentA') {
currentComponent.value = ComponentA;
} else if (componentName === 'ComponentB') {
currentComponent.value = ComponentB;
} else if (componentName === 'AsyncComponentC') {
currentComponent.value = AsyncComponentC;
}
};
// Example content for AsyncComponentC.vue
/*
<template>
<div style="background-color: #ffffe0; padding: 10px;">
<h3>Async Component C</h3>
<p>I was loaded asynchronously!</p>
</div>
</template>
<script setup>
// This component's code will only be fetched when AsyncComponentC is first rendered.
import { ref } from 'vue';
const message = ref('Hello from Async C!');
</script>
*/
</script>
<style scoped>
.component-container {
margin-top: 20px;
border: 1px dashed #ccc;
padding: 15px;
min-height: 50px;
}
</style>
How it works: This snippet demonstrates two powerful Vue 3 features: dynamic components using the `is` attribute and asynchronous components. The `is` attribute allows you to render different components based on a reactive data property, providing flexibility for creating dynamic interfaces. `defineAsyncComponent` enables lazy loading of components, where the component's code is only fetched from the server when it's actually needed, significantly improving initial page load performance, especially for larger applications with many routes or conditional UI elements.