0
0
Vueframework~30 mins

Suspense for async components in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Suspense for Async Components in Vue
📖 Scenario: You are building a Vue app that shows user profiles. The profile data loads slowly from the server. You want to show a loading message while the profile component is loading.
🎯 Goal: Create a Vue app that uses <Suspense> to show a loading message while an async profile component loads.
📋 What You'll Learn
Create a basic Vue app with a root component
Define an async component called UserProfile that simulates loading delay
Use a loadingMessage variable to show while loading
Wrap UserProfile inside <Suspense> with a fallback slot
Ensure the loading message shows until the async component is ready
💡 Why This Matters
🌍 Real World
Many web apps load parts of their UI asynchronously to improve speed and user experience. Using <code>&lt;Suspense&gt;</code> helps show loading states smoothly.
💼 Career
Understanding async components and suspense is important for frontend developers working with Vue to build responsive and user-friendly interfaces.
Progress0 / 4 steps
1
Create the async component UserProfile
Create an async component called UserProfile using defineAsyncComponent that simulates a 2-second delay before resolving. The component should render a <div> with the text User Profile Loaded.
Vue
Hint

Use defineAsyncComponent and return a Promise that resolves after 2 seconds with a simple template.

2
Add a loadingMessage variable
Inside the <script setup>, create a constant called loadingMessage and set it to the string 'Loading user profile...'.
Vue
Hint

Use const loadingMessage = 'Loading user profile...' to create the variable.

3
Use <Suspense> with fallback slot
In the <template>, add a <Suspense> component. Inside it, place the <UserProfile /> component. Add a <template #fallback> slot that displays the loadingMessage variable inside a <div>.
Vue
Hint

Wrap <UserProfile /> inside <Suspense>. Use <template #fallback> to show loadingMessage.

4
Complete the Vue app with import and registration
Add the import statement for Suspense from 'vue' inside <script setup>. Register UserProfile as a component by adding it to the components option in the <script setup> block.
Vue
Hint

Import Suspense from 'vue' alongside defineAsyncComponent.