Vue.js Suspense

Vue.js is a progressive JavaScript framework used for building user interfaces. One of the powerful features introduced in Vue 3 is the Suspense component. This feature is designed to handle asynchronous components gracefully, making it easier to manage loading states in your applications. In this chapter, we will explore Vue.js Suspense from basic concepts to advanced usage, with detailed examples and explanations.

What is Vue.js Suspense?

Suspense is a special component in Vue 3 that allows you to handle asynchronous components by providing a way to display fallback content while waiting for the component to load. It is similar to the Suspense component in React and is particularly useful for managing loading states in a clean and declarative manner.

Key Features:

  • Provides fallback content during asynchronous operations.
  • Simplifies loading state management.
  • Enhances user experience by preventing blank states.

Handling asynchronous operations is a common requirement in modern web applications. Without Suspense, you might need to write extensive boilerplate code to manage loading states and error handling. Suspense simplifies this process by allowing you to specify fallback content directly within your templates.

Benefits:

  • Cleaner code with less boilerplate.
  • Improved user experience with better handling of loading states.
  • Easier error management in asynchronous components.

Why Use Vue.js Suspense?

Before using Suspense, ensure that you are using Vue 3, as this feature is not available in Vue 

Installation

First, make sure you have Vue 3 installed. If not, you can install it via npm or yarn:

				
					npm install vue@next
# or
yarn add vue@next

				
			

Basic Setup

Import Vue and create a new Vue 3 app:

				
					import { createApp } from 'vue';
import App from './App.vue';

createApp(App).mount('#app');

				
			

Basic Usage

Simple Example

Here’s a simple example to illustrate the usage of Suspense. Let’s create a component that fetches data from an API.

AsyncComponent.vue

				
					<template>
  <div>
    <h2>Data from API:</h2>
    <pre>{{ data }}</pre></div>
</template> <script type="litespeed/javascript">export default{data(){return{data:null,}},async setup(){const response=await fetch('https://api.example.com/data');const result=await response.json();return{data:result}},}</script> 

App.vue

				
					<template>
  <Suspense>
    <template #default>
      <AsyncComponent />
    </template>
    <template #fallback>
      <div>Loading...</div>
    </template>
  </Suspense>
</template> <script type="litespeed/javascript">import AsyncComponent from './components/AsyncComponent.vue';export default{components:{AsyncComponent,},}</script> 
				
			

Explanation

  • Suspense has two slots: default and fallback.
  • The default slot contains the asynchronous component.
  • The fallback slot contains the content to display while the asynchronous component is loading.

Advanced Usage

Nested Suspense

You can nest Suspense components to handle multiple asynchronous operations independently.

ParentComponent.vue

				
					<template>
  <Suspense>
    <template #default>
      <ChildComponent />
    </template>
    <template #fallback>
      <div>Loading ChildComponent...</div>
    </template>
  </Suspense>
</template> <script type="litespeed/javascript">import ChildComponent from './ChildComponent.vue';export default{components:{ChildComponent,},}</script> 
				
			

ChildComponent.vue

				
					<template>
  <Suspense>
    <template #default>
      <AsyncDataComponent />
    </template>
    <template #fallback>
      <div>Loading Data...</div>
    </template>
  </Suspense>
</template> <script type="litespeed/javascript">import AsyncDataComponent from './AsyncDataComponent.vue';export default{components:{AsyncDataComponent,},}</script> 
				
			

Explanation

  • By nesting Suspense components, you can handle loading states for different parts of your application independently.

Handling Errors with Suspense

Suspense also provides a way to handle errors in asynchronous components.

ErrorBoundary.vue

				
					<template>
  <div v-if="error">
    <h2>An error occurred:</h2>
    <pre>{{ error }}</pre></div><div v-else>
<slot></slot></div>
</template> <script type="litespeed/javascript">export default{data(){return{error:null,}},errorCaptured(err){this.error=err.toString();return!1},}</script> 

Usage with Suspense

				
					<template>
  <Suspense>
    <template #default>
      <ErrorBoundary>
        <AsyncComponent />
      </ErrorBoundary>
    </template>
    <template #fallback>
      <div>Loading...</div>
    </template>
  </Suspense>
</template> <script type="litespeed/javascript">import AsyncComponent from './components/AsyncComponent.vue';import ErrorBoundary from './components/ErrorBoundary.vue';export default{components:{AsyncComponent,ErrorBoundary,},}</script> 
				
			

Explanation

  • ErrorBoundary captures errors in its child components and displays an error message.
  • Use ErrorBoundary inside Suspense to handle errors gracefully.

Real-world Examples

Fetching User Data

Imagine an application that fetches user data and displays it.

UserComponent.vue

				
					<template>
  <div>
    <h2>User Profile</h2>
    <p>Name: {{ user.name }}</p>
    <p>Email: {{ user.email }}</p>
  </div>
</template> <script type="litespeed/javascript">export default{data(){return{user:null,}},async setup(){const response=await fetch('https://api.example.com/user');const user=await response.json();return{user}},}</script> 
				
			

App.vue

				
					<template>
  <Suspense>
    <template #default>
      <UserComponent />
    </template>
    <template #fallback>
      <div>Loading user data...</div>
    </template>
  </Suspense>
</template> <script type="litespeed/javascript">import UserComponent from './components/UserComponent.vue';export default{components:{UserComponent,},}</script> 
				
			

Explanation

  • UserComponent fetches user data from an API and displays it.
  • Suspense manages the loading state and displays a loading message while the data is being fetched.

Suspense in Vue.js is a powerful tool for managing asynchronous operations and improving the user experience. By using Suspense, you can handle loading states and errors in a clean and declarative way, making your code more maintainable and robust. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India