How to Use defineAsyncComponent in Vue for Lazy Loading
Use
defineAsyncComponent from Vue to load components lazily by passing a function that imports the component. This helps improve performance by loading components only when needed.Syntax
The defineAsyncComponent function takes a loader function that returns a dynamic import of the component. It returns a component that Vue loads asynchronously when rendered.
defineAsyncComponent(() => import('./MyComponent.vue')): LoadsMyComponent.vuelazily.- You can also pass an options object for loading and error states.
javascript
import { defineAsyncComponent } from 'vue'; const AsyncComp = defineAsyncComponent(() => import('./MyComponent.vue'));
Example
This example shows how to use defineAsyncComponent to load a component only when it is needed, improving initial load speed.
javascript
import { createApp, defineAsyncComponent } from 'vue'; const AsyncHello = defineAsyncComponent(() => import('./Hello.vue')); const App = { components: { AsyncHello }, template: `<div><h1>Async Component Demo</h1><AsyncHello /></div>` }; createApp(App).mount('#app');
Output
<div><h1>Async Component Demo</h1><p>Hello from async component!</p></div>
Common Pitfalls
- Not using
defineAsyncComponentand importing components normally causes all components to load upfront, losing lazy loading benefits. - Forgetting to handle loading or error states can cause poor user experience during slow network.
- Using relative paths incorrectly in the import function can cause module not found errors.
javascript
/* Wrong way: normal import loads immediately */ import Hello from './Hello.vue'; /* Right way: lazy load with defineAsyncComponent */ import { defineAsyncComponent } from 'vue'; const Hello = defineAsyncComponent(() => import('./Hello.vue'));
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Basic Usage | Load component lazily with a dynamic import | defineAsyncComponent(() => import('./Comp.vue')) |
| Loading State | Show a component while loading | { loader: () => import('./Comp.vue'), loadingComponent: LoadingComp } |
| Error Handling | Show a component on load failure | { loader: () => import('./Comp.vue'), errorComponent: ErrorComp } |
| Delay | Delay before showing loading component | { delay: 200 } |
| Timeout | Timeout for loading before error | { timeout: 3000 } |
Key Takeaways
Use defineAsyncComponent to load Vue components lazily and improve app performance.
Pass a function returning a dynamic import to defineAsyncComponent.
Handle loading and error states for better user experience.
Avoid importing components normally if you want lazy loading benefits.
Check import paths carefully to prevent module errors.