JAVASCRIPT
Lazily Loading Components with Vue 3 Asynchronous Imports
Boost application performance by implementing asynchronous components in Vue 3, enabling lazy loading to reduce initial bundle size and improve perceived page speed.
// src/components/HeavyComponent.vue
<template>
<div style="padding: 20px; border: 1px dashed blue; margin-top: 20px;">
<h3>Heavy Component Loaded!</h3>
<p>This component was loaded asynchronously, reducing initial bundle size.</p>
<img src="https://via.placeholder.com/150/0000FF/FFFFFF?text=Async+Loaded" alt="Async Placeholder" />
</div>
</template>
<script setup>
import { onMounted } from 'vue';
onMounted(() => {
console.log('HeavyComponent mounted!');
});
</script>
// src/App.vue
<template>
<div>
<h1>Asynchronous Components Demo</h1>
<p>Click the button to load a component lazily:</p>
<button @click="showHeavyComponent = true" :disabled="showHeavyComponent">
Load Heavy Component
</button>
<div v-if="showHeavyComponent">
<Suspense>
<template #default>
<AsyncHeavyComponent />
</template>
<template #fallback>
<div>Loading heavy component...</div>
</template>
</Suspense>
</div>
</div>
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
const showHeavyComponent = ref(false);
// Define the async component. The component will only be fetched when rendered.
const AsyncHeavyComponent = defineAsyncComponent(() =>
import('./components/HeavyComponent.vue')
);
</script>
How it works: Vue 3's `defineAsyncComponent` allows for lazy loading components, meaning their code is only fetched from the server and parsed when they are actually needed, rather than being included in the initial bundle. This snippet demonstrates how to define an async component and use it within a parent. The `Suspense` component, along with its `#fallback` slot, provides a way to show loading states while the async component is being fetched, greatly improving perceived performance for complex applications.