0
0
VueHow-ToBeginner · 3 min read

How to Use Suspense in Vue: Syntax and Examples

In Vue, use the <Suspense> component to wrap async components and provide fallback content while they load. Place your async component inside <Suspense> and add a <template #fallback> block to show loading UI until the async component is ready.
📐

Syntax

The <Suspense> component wraps async components and shows fallback content while waiting. Inside <Suspense>, place your async component normally. Use <template #fallback> to define what the user sees during loading.

Example parts:

  • <Suspense>: The wrapper component.
  • Default slot: Your async component.
  • <template #fallback>: Loading UI shown while waiting.
vue
<Suspense>
  <AsyncComponent />
  <template #fallback>
    <div>Loading...</div>
  </template>
</Suspense>
💻

Example

This example shows a simple async component wrapped in <Suspense>. While the async component loads, the fallback text "Loading..." is displayed. When ready, the async component content replaces the fallback.

vue
<template>
  <Suspense>
    <AsyncHello />
    <template #fallback>
      <p>Loading...</p>
    </template>
  </Suspense>
</template>

<script setup>
import { defineAsyncComponent } from 'vue'

const AsyncHello = defineAsyncComponent(() =>
  new Promise(resolve => {
    setTimeout(() => {
      resolve({
        template: '<h1>Hello from async component!</h1>'
      })
    }, 2000)
  })
)
</script>
Output
Loading... (for 2 seconds), then shows: Hello from async component!
⚠️

Common Pitfalls

Common mistakes when using <Suspense> include:

  • Not providing a #fallback slot, so users see nothing while loading.
  • Wrapping synchronous components unnecessarily, which adds overhead.
  • Expecting <Suspense> to handle errors; it only handles loading states.

Always use defineAsyncComponent for async components inside <Suspense>.

vue
<!-- Wrong: no fallback slot -->
<Suspense>
  <AsyncComponent />
</Suspense>

<!-- Right: with fallback -->
<Suspense>
  <AsyncComponent />
  <template #fallback>
    <div>Loading...</div>
  </template>
</Suspense>
📊

Quick Reference

FeatureDescription
Wraps async components to manage loading UI
#fallback slotDefines content shown while async component loads
defineAsyncComponentCreates async components for Suspense
Error handlingSuspense does not handle errors; use error boundaries
Use caseImprove UX by showing loading states for async components

Key Takeaways

Wrap async components in to show fallback UI while loading.
Always provide a #fallback slot inside for loading content.
Use defineAsyncComponent to create components that load asynchronously.
Suspense handles loading states but not errors; handle errors separately.
Avoid wrapping synchronous components with to keep code simple.