0
0
Vueframework~30 mins

Testing async behavior in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing async behavior
📖 Scenario: You are building a simple Vue 3 component that fetches user data asynchronously and displays it. You want to test the async behavior to ensure the data loads correctly.
🎯 Goal: Create a Vue 3 component that fetches user data asynchronously using setTimeout to simulate a delay, then test that the data is displayed after loading.
📋 What You'll Learn
Use Vue 3 Composition API with <script setup>
Create a reactive variable to hold user data
Simulate async data fetch with setTimeout
Display loading text while waiting
Show user name after data loads
💡 Why This Matters
🌍 Real World
Many web apps load data from servers asynchronously. Showing loading states improves user experience.
💼 Career
Understanding async data handling and testing is essential for frontend developers working with Vue or similar frameworks.
Progress0 / 4 steps
1
DATA SETUP: Create reactive user data variable
In a Vue 3 <script setup> block, import ref from 'vue' and create a reactive variable called user initialized to null.
Vue
Hint

Use ref(null) to create a reactive variable that starts empty.

2
CONFIGURATION: Create loading state variable
Add a reactive variable called loading initialized to true to track if data is loading.
Vue
Hint

Use ref(true) to indicate loading starts as true.

3
CORE LOGIC: Simulate async data fetch with setTimeout
Use setTimeout to simulate fetching user data after 1 second. Inside the timeout callback, set user.value to { name: 'Alice' } and set loading.value to false.
Vue
Hint

Use setTimeout with 1000 milliseconds delay to simulate async fetch.

4
COMPLETION: Add template to show loading and user name
Add a Vue template that shows Loading... text when loading is true, and shows User: {{ user.name }} when loading is false.
Vue
Hint

Use v-if and v-else to show loading text or user name.