JAVASCRIPT
Vue 3 Suspense for Async Components
Implement elegant loading states for asynchronous components using Vue 3's Suspense, providing a smooth user experience while data or components load.
<!-- App.vue -->
<template>
<h1>My Application</h1>
<Suspense>
<template #default>
<AsyncComponent />
</template>
<template #fallback>
<div>Loading Async Component...</div>
</template>
</Suspense>
</template>
<script setup>
import { defineAsyncComponent } from 'vue';
// Simulate an async component loading
const AsyncComponent = defineAsyncComponent(() =>
new Promise(resolve => {
setTimeout(() => {
resolve({
template: '<div><h2>Async Content Loaded!</h2><p>This content appeared after a delay.</p></div>'
});
}, 2000); // 2 second delay
})
);
</script>
How it works: The Vue 3 `<Suspense>` component allows you to orchestrate asynchronous dependencies in your component tree. It provides a default slot for the actual asynchronous content (like a `defineAsyncComponent` or a component with an async `setup` function) and a `fallback` slot to display loading content while the default content is being resolved. This simplifies handling loading states and error boundaries for large parts of your application, improving user experience by providing immediate feedback.