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
#fallbackslot, 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
| Feature | Description |
|---|---|
| Wraps async components to manage loading UI | |
| #fallback slot | Defines content shown while async component loads |
| defineAsyncComponent | Creates async components for Suspense |
| Error handling | Suspense does not handle errors; use error boundaries |
| Use case | Improve 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.