JAVASCRIPT
Efficient Dynamic Component Loading in Vue 3
Discover how to dynamically load components in Vue 3 using the 'is' attribute and 'defineAsyncComponent' for improved performance and flexible UI rendering.
// components/LazyComponentA.vue
<template>
<div style="border: 1px solid blue; padding: 10px; margin: 5px;">
<h3>Lazy Component A</h3>
<p>This component was loaded asynchronously!</p>
</div>
</template>
// components/LazyComponentB.vue
<template>
<div style="border: 1px solid green; padding: 10px; margin: 5px;">
<h3>Lazy Component B</h3>
<p>Another async component, loaded dynamically.</p>
</div>
</template>
// App.vue
<template>
<div>
<h2>Dynamic & Async Components</h2>
<button @click="currentComponent = 'LazyComponentA'">Load A</button>
<button @click="currentComponent = 'LazyComponentB'">Load B</button>
<p>Currently active component: {{ currentComponent || 'None' }}</p>
<div style="margin-top: 20px;">
<component :is="activeComponent" />
</div>
</div>
</template>
<script setup>
import { ref, computed, defineAsyncComponent } from 'vue';
import LoadingSpinner from './LoadingSpinner.vue'; // A simple loading component
import ErrorMessage from './ErrorMessage.vue'; // A simple error component
const currentComponent = ref('');
const AsyncComponentA = defineAsyncComponent({
loader: () => import('./components/LazyComponentA.vue'),
loadingComponent: LoadingSpinner,
errorComponent: ErrorMessage,
delay: 200, // delay before showing loading component (ms)
timeout: 3000 // error if loader takes longer than 3s (ms)
});
const AsyncComponentB = defineAsyncComponent(() => import('./components/LazyComponentB.vue'));
const activeComponent = computed(() => {
if (currentComponent.value === 'LazyComponentA') {
return AsyncComponentA;
} else if (currentComponent.value === 'LazyComponentB') {
return AsyncComponentB;
} else {
return null;
}
});
</script>
How it works: This snippet illustrates how to use Vue 3's `is` attribute with `defineAsyncComponent` for dynamic and efficient component loading. `defineAsyncComponent` allows components to be loaded only when needed, reducing initial bundle size. The `component` tag with the `:is` prop dynamically renders the component corresponding to the `activeComponent` computed property. Options for loading, error, delay, and timeout provide a robust async loading experience.