What is Suspense in Vue: Explanation and Example
Suspense in Vue is a built-in component that lets you wait for async components or data to load before showing the final content. It shows fallback content while waiting, improving user experience during loading times.How It Works
Imagine you order a meal at a restaurant. While the kitchen prepares your food, you wait at the table. Vue's Suspense works similarly: it shows a temporary placeholder (fallback) while waiting for some parts of the page to be ready.
When you use async components or fetch data that takes time, Suspense displays fallback content like a loading spinner. Once everything is ready, it replaces the fallback with the actual content smoothly.
This helps avoid showing empty or broken parts on the page and gives users a clear sign that something is loading.
Example
This example shows how Suspense wraps an async component and displays a loading message until the component is ready.
<template>
<Suspense>
<template #default>
<AsyncComponent />
</template>
<template #fallback>
<p>Loading component, please wait...</p>
</template>
</Suspense>
</template>
<script setup>
import { defineAsyncComponent } from 'vue'
const AsyncComponent = defineAsyncComponent(() =>
new Promise(resolve => {
setTimeout(() => {
resolve({
template: '<div><strong>Async Component Loaded!</strong></div>'
})
}, 2000)
})
)
</script>When to Use
Use Suspense when you have components or data that load asynchronously and you want to show a friendly loading state instead of blank or broken UI. It is perfect for:
- Lazy-loading components to reduce initial page size.
- Fetching data before showing parts of the UI.
- Improving user experience by showing clear loading indicators.
For example, in a dashboard app, you can wrap slow-loading widgets in Suspense so users see a spinner instead of empty space.
Key Points
- Suspense handles async components or data loading in Vue.
- It shows fallback content while waiting.
- Once ready, it replaces fallback with the actual content.
- Improves user experience by avoiding empty or broken UI.
- Works well with lazy-loaded components and async data fetching.
Key Takeaways
Suspense lets you show fallback content while async components load.Suspense with fallback slots for smooth loading.Suspense automatically shows it.