JAVASCRIPT
Lazy Loading Vue 3 Components with `defineAsyncComponent`
Improve Vue 3 application performance by lazy loading components only when needed using `defineAsyncComponent`, reducing initial bundle size and load times.
// App.vue
<template>
<div>
<button @click="showModal = !showModal">Toggle Modal</button>
<Suspense>
<template #default>
<LazyModal v-if="showModal" @close="showModal = false" />
</template>
<template #fallback>
<div>Loading modal...</div>
</template>
</Suspense>
</div>
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
const showModal = ref(false);
const LazyModal = defineAsyncComponent(() =>
import('./LazyModal.vue')
);
</script>
// LazyModal.vue
<template>
<div class="modal-overlay" @click.self="$emit('close')">
<div class="modal-content">
<h2>Lazy Loaded Modal</h2>
<p>This content was loaded asynchronously.</p>
<button @click="$emit('close')">Close</button>
</div>
</div>
</template>
<script setup>
// No script logic needed for this simple modal component, just emits close.
</script>
<style scoped>
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>
How it works: This snippet demonstrates how to lazy load a Vue 3 component using `defineAsyncComponent`. The `LazyModal` component is only fetched and rendered when `showModal` is true, significantly reducing the initial bundle size. It's wrapped in a `<Suspense>` component to provide a fallback loading state while the async component is being resolved, improving user experience during network delays.