What is Async Component in Vue: Explanation and Example
async component in Vue is a component that loads only when needed, instead of loading with the whole app. This helps make apps faster by splitting code and loading parts on demand.How It Works
Imagine you have a big book but you only want to read one chapter at a time. Instead of carrying the whole book everywhere, you carry just the chapter you need. Async components in Vue work the same way. They let your app load only the parts (components) it needs right now, instead of loading everything at once.
When Vue sees an async component, it waits to download and prepare that component until it is actually needed, like when a user visits a certain page or clicks a button. This makes the app start faster and saves data because it doesn’t load unused parts immediately.
Example
This example shows how to define and use an async component in Vue. The component AsyncHello loads only when it is displayed.
import { defineAsyncComponent, createApp } from 'vue'; const AsyncHello = defineAsyncComponent(() => import('./Hello.vue') ); const App = { components: { AsyncHello }, template: `<div><h1>Main App</h1><AsyncHello /></div>` }; createApp(App).mount('#app');
When to Use
Use async components when your app has large or many components that are not needed right away. For example, if you have a settings page or a complex chart that users visit sometimes, loading them only when needed speeds up the initial app load.
This is especially helpful for apps on slow networks or mobile devices, where loading everything at once can cause delays or use too much data.
Key Points
- Async components load only when needed, improving app speed.
- They help split your app into smaller pieces called chunks.
- Vue’s
defineAsyncComponentis used to create async components. - Great for large apps or rarely used parts.