JAVASCRIPT
Lazy Loading Components with defineAsyncComponent in Vue 3
Optimize Vue 3 application performance by implementing lazy loading for components using `defineAsyncComponent`, reducing initial bundle size and improving load times for enhanced user experience.
// 1. Define an async component (e.g., in components/AsyncComponent.vue)
/*
<template>
<div class="async-component">
<h2>This is an Asynchronously Loaded Component</h2>
<p>It was loaded only when needed!</p>
</div>
</template>
<script setup>
import { onMounted } from 'vue';
onMounted(() => {
console.log('AsyncComponent mounted!');
});
</script>
<style scoped>
.async-component {
border: 1px dashed #ccc;
padding: 15px;
margin-top: 20px;
background-color: #f9f9f9;
}
</style>
*/
// 2. Use defineAsyncComponent to lazy load it in a parent component
// (e.g., in App.vue)
<template>
<div>
<h1>Parent Component</h1>
<button @click="showAsyncComponent = !showAsyncComponent">
{{ showAsyncComponent ? 'Hide' : 'Show' }} Async Component
</button>
<div v-if="showAsyncComponent">
<Suspense>
<template #default>
<LazyLoadedComponent />
</template>
<template #fallback>
<div>Loading Async Component...</div>
</template>
</Suspense>
</div>
</div>
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
// Define the component to be lazy-loaded
const LazyLoadedComponent = defineAsyncComponent(() =>
import('./components/AsyncComponent.vue')
);
const showAsyncComponent = ref(false);
</script>
How it works: This snippet demonstrates how to lazy load components in Vue 3 using `defineAsyncComponent`. Instead of bundling `AsyncComponent.vue` with the initial application code, it's loaded only when it's actually rendered (in this case, when `showAsyncComponent` is true). This significantly reduces the initial JavaScript bundle size, leading to faster page load times. The `Suspense` component is used to provide a fallback loading state while the asynchronous component is being fetched, improving the user experience during network delays.