JAVASCRIPT

Manage Asynchronous Components with Vue 3 Suspense

Utilize Vue 3's `Suspense` component to gracefully handle asynchronous dependencies, displaying a fallback loading state while components are being fetched or resolved.

// src/components/AsyncDataDisplay.vue
<template>
  <div>
    <h3>Data Loaded!</h3>
    <p>Message: {{ data.message }}</p>
  </div>
</template>

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

const data = ref(null);

// Simulate an async data fetch
await new Promise(resolve => setTimeout(resolve, 2000));
data.value = { message: 'Hello from async component!' };
</script>

// src/App.vue
<template>
  <div>
    <h1>Welcome to My App</h1>
    <Suspense>
      <!-- Main content to show once async component is loaded -->
      <template #default>
        <AsyncDataDisplay />
      </template>

      <!-- Content to show while async component is loading -->
      <template #fallback>
        <div>Loading async data...</div>
      </template>
    </Suspense>
  </div>
</template>

<script setup>
import { defineAsyncComponent } from 'vue';
// AsyncDataDisplay will be loaded asynchronously
const AsyncDataDisplay = defineAsyncComponent(() => import('./components/AsyncDataDisplay.vue'));
</script>
How it works: This snippet showcases Vue 3's `Suspense` component, designed to orchestrate asynchronous operations. `AsyncDataDisplay.vue` is an asynchronous component (simulating a data fetch with `await`) that will take time to render. In `App.vue`, `Suspense` wraps `AsyncDataDisplay`. While `AsyncDataDisplay` is loading, the content in the `#fallback` slot is displayed. Once `AsyncDataDisplay` resolves, it replaces the fallback content, providing a smooth user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs