JAVASCRIPT
Asynchronously Load Components for Better Performance
Learn how to dynamically import and render Vue 3 components only when needed, significantly improving initial load times and application performance through code splitting.
import { defineAsyncComponent, ref } from 'vue';
const AsyncComponent = defineAsyncComponent(() =>
import('./HeavyComponent.vue')
);
// In a Vue component (.vue file):
<template>
<div>
<button @click="showComponent = !showComponent">Toggle Heavy Component</button>
<Suspense>
<template #default>
<AsyncComponent v-if="showComponent" />
</template>
<template #fallback>
<div>Loading...</div>
</template>
</Suspense>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { defineAsyncComponent } from 'vue';
const HeavyComponent = defineAsyncComponent(() =>
import('./HeavyComponent.vue')
);
const showComponent = ref(false);
</script>
<!-- HeavyComponent.vue (example) -->
<template>
<div style="border: 1px solid blue; padding: 10px; margin-top: 10px;">
<h3>This is a heavy component loaded asynchronously!</h3>
<p>It could contain complex logic or large libraries.</p>
</div>
</template>
<script setup>
// Simulate a delay for demonstration
await new Promise(resolve => setTimeout(resolve, 1000));
</script>
How it works: This snippet demonstrates how to use Vue 3's `defineAsyncComponent` to load components lazily. Instead of bundling `HeavyComponent.vue` with the initial application payload, it's fetched only when it's actually rendered. This improves initial page load times and reduces bundle size. The `<Suspense>` component works in conjunction with async components, allowing you to display a fallback loading state while the asynchronous component is being loaded, providing a better user experience. The `v-if` ensures the component is only mounted (and thus loaded) when needed.