JAVASCRIPT

Handling Asynchronous Components with Vue 3 Suspense

Discover how to manage asynchronous component loading and provide fallback content using Vue 3's built-in Suspense component for better user experience.

// components/AsyncDataDisplay.vue
<template>
  <div>
    <h3>Fetched Data:</h3>
    <p>{{ data }}</p>
  </div>
</template>

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

const data = ref('Loading...');

// Simulate an async operation, e.g., fetching data from an API
await new Promise(resolve => setTimeout(resolve, 2000));

data.value = 'Data successfully loaded after 2 seconds!';
</script>

// App.vue (Parent Component)
<template>
  <h1>Vue 3 Suspense Example</h1>
  <Suspense>
    <template #default>
      <AsyncDataDisplay />
    </template>
    <template #fallback>
      <div>
        <p>Loading async component...</p>
        <img src="https://i.giphy.com/media/3oEjI6SIIHBc5qR5Vm/giphy.gif" alt="Loading" style="width: 50px;" />
      </div>
    </template>
  </Suspense>
  <p>Content below Suspense (renders immediately)</p>
</template>

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

// Although defineAsyncComponent is typically used, for components with async setup()
// Vue 3 automatically treats them as async. No explicit defineAsyncComponent call needed
// when using <script setup> and top-level await.
import AsyncDataDisplay from './components/AsyncDataDisplay.vue';
</script>
How it works: This snippet showcases Vue 3's `Suspense` component for managing asynchronous components and providing a fallback loading state. The `AsyncDataDisplay` component uses `await` in its `script setup` to simulate an asynchronous data fetch. The parent `App.vue` wraps `AsyncDataDisplay` with `Suspense`, displaying content from the `#fallback` slot while the async component is loading, and switching to the `#default` slot once it resolves.

Need help integrating this into your project?

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

Hire DigitalCodeLabs