0
0
Vueframework~5 mins

Async components for lazy loading in Vue

Choose your learning style9 modes available
Introduction

Async components let Vue load parts of your app only when needed. This makes your app faster and saves data.

When you have big components that slow down the start of your app.
If some parts of your app are rarely used and can wait to load.
To improve user experience by showing content faster on first load.
When you want to split your app into smaller pieces for easier updates.
Syntax
Vue
const AsyncComponent = defineAsyncComponent(() => import('./MyComponent.vue'))
Use defineAsyncComponent from Vue to create async components.
The component is loaded only when it is rendered for the first time.
Examples
Basic async component loading a file when needed.
Vue
import { defineAsyncComponent } from 'vue'

const AsyncComp = defineAsyncComponent(() => import('./AsyncComp.vue'))
Async component with a loading spinner shown after 200ms delay.
Vue
import { defineAsyncComponent } from 'vue'

const AsyncComp = defineAsyncComponent({
  loader: () => import('./AsyncComp.vue'),
  loadingComponent: LoadingSpinner,
  delay: 200
})
Shows an error message if loading takes more than 3 seconds.
Vue
import { defineAsyncComponent } from 'vue'

const AsyncComp = defineAsyncComponent({
  loader: () => import('./AsyncComp.vue'),
  errorComponent: ErrorMessage,
  timeout: 3000
})
Sample Program

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.

Vue
<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>
OutputSuccess
Important Notes

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.

Summary

Async components load parts of your app only when needed.

Use defineAsyncComponent to create them easily.

Combine with <Suspense> for smooth loading states.