Introduction
Async components let Vue load parts of your app only when needed. This makes your app faster and saves data.
Async components let Vue load parts of your app only when needed. This makes your app faster and saves data.
const AsyncComponent = defineAsyncComponent(() => import('./MyComponent.vue'))
defineAsyncComponent from Vue to create async components.import { defineAsyncComponent } from 'vue' const AsyncComp = defineAsyncComponent(() => import('./AsyncComp.vue'))
import { defineAsyncComponent } from 'vue' const AsyncComp = defineAsyncComponent({ loader: () => import('./AsyncComp.vue'), loadingComponent: LoadingSpinner, delay: 200 })
import { defineAsyncComponent } from 'vue' const AsyncComp = defineAsyncComponent({ loader: () => import('./AsyncComp.vue'), errorComponent: ErrorMessage, timeout: 3000 })
This example shows a button that toggles an async component called Hello.vue. The component loads only when shown. While loading, a fallback message appears.
<template> <button @click="show = !show">Toggle Async Component</button> <Suspense> <template #default> <AsyncHello v-if="show" /> </template> <template #fallback> <p>Loading component...</p> </template> </Suspense> </template> <script setup> import { ref, defineAsyncComponent } from 'vue' const show = ref(false) const AsyncHello = defineAsyncComponent(() => import('./Hello.vue')) </script>
Always provide fallback UI inside <Suspense> to improve user experience.
Async components help reduce initial load but add a small delay when first shown.
Use error and loading components to handle slow or failed loads gracefully.
Async components load parts of your app only when needed.
Use defineAsyncComponent to create them easily.
Combine with <Suspense> for smooth loading states.
defineAsyncComponent in Vue?defineAsyncComponentdefineAsyncComponent with a function returning an import promise.defineAsyncComponent(() => import('...')).const AsyncComp = defineAsyncComponent(() => new Promise(resolve => {
setTimeout(() => resolve({ template: 'Loaded!' }), 2000)
}))
export default {
components: { AsyncComp },
template: `
Loading...
`
}import { defineAsyncComponent } from 'vue'
const AsyncComp = defineAsyncComponent(() => import('./MyComp.vue'))
export default {
components: { AsyncComp },
template: ``
}<Suspense> to show fallback during loading.<Suspense> wrapper, so no loading state is handled.CompA and CompB, but only show CompB after CompA finishes loading. How can you achieve this using Vue async components and Suspense?CompB to appear only after CompA finishes loading.CompA in Suspense; in CompA's mounted hook, dynamically render CompB (async) inside its own Suspense for true sequential loading.CompB in CompA's default slot loads it immediately upon CompA resolution.CompA in a Suspense with fallback, then in CompA's mounted hook, render CompB inside another Suspense -> Option DPass the test and this pattern moves unknown