#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 29 of 37medium

What is Suspense in Vue?

Handling async dependencies.

What You'll Learn

  • Suspense basics
  • Async setup
  • Error handling

Basic Suspense

code.txtVUE
<template>
  <Suspense>
    <template #default>
      <AsyncComponent />
    </template>
    <template #fallback>
      <LoadingSpinner />
    </template>
  </Suspense>
</template>

Async Setup

code.txtVUE
<!-- AsyncComponent.vue -->
<script setup>
const data = await fetch('/api/data').then(r => r.json())
</script>

<template>
  <div>{{ data }}</div>
</template>

Multiple Async Components

code.txtVUE
<Suspense>
  <template #default>
    <div>
      <UserProfile />
      <UserPosts />
    </div>
  </template>
  <template #fallback>
    <Loading />
  </template>
</Suspense>

Error Handling

code.txtVUE
<template>
  <ErrorBoundary>
    <Suspense>
      <AsyncComponent />
      <template #fallback>Loading...</template>
    </Suspense>
  </ErrorBoundary>
</template>

<script setup>
import { onErrorCaptured } from 'vue'

onErrorCaptured((err) => {
  console.error(err)
  return false // Stop propagation
})
</script>