JAVASCRIPT

Gracefully Handle Asynchronous Components with Vue 3 Suspense

Implement Vue 3's `Suspense` component to manage loading states and display fallback content for asynchronous components using `async setup` or lazy loading.

// AsyncDataLoader.vue
<template>
  <div>
    <h3>Data Loaded!</h3>
    <p>Message: {{ data.message }}</p>
    <p>Count: {{ data.count }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const data = ref(null);

// Simulate an async data fetch
await new Promise(resolve => setTimeout(resolve, 2000)); // Simulate 2-second delay

data.value = {
  message: 'Hello from async component!',
  count: Math.floor(Math.random() * 100)
};
</script>

// App.vue (Parent Component)
<template>
  <div>
    <h1>App using Suspense</h1>
    <button @click="toggleComponent">Toggle Async Component</button>

    <Suspense v-if="showAsync">
      <!-- Default content while async component is loading -->
      <template #fallback>
        <div style="color: blue;">Loading async data... Please wait.</div>
      </template>

      <!-- The actual async component -->
      <template #default>
        <AsyncDataLoader />
      </template>
    </Suspense>
    <div v-else>
      Async component is hidden.
    </div>
  </div>
</template>

<script setup>
import { ref, defineAsyncComponent } from 'vue';

// This is the async component. In a real app, it would usually be imported
// with defineAsyncComponent for chunking, but for simple async setup
// it can be directly imported if not lazy-loaded.
// const AsyncDataLoader = defineAsyncComponent(() => import('./AsyncDataLoader.vue'));
import AsyncDataLoader from './AsyncDataLoader.vue'; // Using direct import for simpler demo

const showAsync = ref(false);

function toggleComponent() {
  showAsync.value = !showAsync.value;
}
</script>
How it works: This snippet demonstrates Vue 3's `Suspense` component for managing asynchronous component loading states. `Suspense` wraps components that have `async setup()` or are lazy-loaded via `defineAsyncComponent`. It requires two template slots: `#fallback` for content displayed while the async component is loading, and `#default` for the actual async component. The `AsyncDataLoader` component uses `await` directly within its `script setup` block to simulate an asynchronous data fetch. `Suspense` automatically renders the fallback until the `await` operation in `AsyncDataLoader` resolves, providing a smooth user experience for loading potentially slow components.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs