JAVASCRIPT
Handling Asynchronous Component Loading with Vue 3 Suspense
Gracefully manage the loading states of asynchronous components or data fetching in Vue 3 using the built-in <Suspense> component, providing a smooth user experience.
<!-- AsyncComponent.vue -->
<template>
<div>
<h3>Asynchronously Loaded Data:</h3>
<p>{{ data }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const data = ref('Loading...');
// Simulate an async operation (e.g., API call)
await new Promise(resolve => setTimeout(resolve, 2000));
data.value = 'Data fetched successfully!';
</script>
<!-- App.vue (Usage Example) -->
<template>
<div>
<h1>Vue 3 Suspense Example</h1>
<Suspense>
<!-- Main content (AsyncComponent) -->
<template #default>
<AsyncComponent />
</template>
<!-- Fallback content while AsyncComponent is loading -->
<template #fallback>
<div>Loading Async Component...</div>
</template>
</Suspense>
</div>
</template>
<script setup>
import { defineAsyncComponent } from 'vue';
// Define an async component (can be a component with top-level await)
const AsyncComponent = defineAsyncComponent(() => import('./AsyncComponent.vue'));
// Or, if AsyncComponent.vue itself uses top-level await,
// you can just import it directly:
// import AsyncComponent from './AsyncComponent.vue';
</script>
How it works: This snippet demonstrates how to use Vue 3's `<Suspense>` component to manage the loading state of asynchronous components. The `AsyncComponent.vue` uses `await` at the top level in its `<script setup>` block, making it an asynchronous component. The parent component then wraps this `AsyncComponent` within `<Suspense>`. While the `AsyncComponent` is resolving its asynchronous dependencies (like an API call), the content of the `#fallback` slot is displayed. Once the `AsyncComponent` is ready, it replaces the fallback content, providing a smooth user experience by preventing flashing or broken layouts during loading.