0
0
Vueframework~30 mins

Loading states pattern in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Loading States Pattern in Vue
📖 Scenario: You are building a simple Vue app that fetches user data from an API. To improve user experience, you want to show a loading message while the data is being fetched.
🎯 Goal: Create a Vue component that shows a loading message while fetching data and then displays the user name once loaded.
📋 What You'll Learn
Use Vue 3 Composition API with <script setup>
Create a reactive loading signal to track loading state
Create a reactive user object to hold fetched data
Simulate data fetching with setTimeout
Show Loading... text while loading is true
Show user name after loading is false
💡 Why This Matters
🌍 Real World
Loading states are common in web apps to inform users that data is being fetched or processed, preventing confusion or frustration.
💼 Career
Understanding loading states and reactive UI updates is essential for frontend developers building responsive and user-friendly applications.
Progress0 / 4 steps
1
Setup reactive user data
Create a Vue component with <script setup> and define a reactive variable called user initialized to an empty object {}.
Vue
Need a hint?

Use reactive from Vue to create a reactive object called user.

2
Add loading state variable
Add a reactive boolean variable called loading initialized to true inside the <script setup> section.
Vue
Need a hint?

Use ref from Vue to create a boolean loading variable set to true.

3
Simulate data fetching and update states
Inside <script setup>, use setTimeout to simulate fetching data after 2 seconds. Inside the timeout callback, set user.name to 'Alice' and set loading.value to false.
Vue
Need a hint?

Use setTimeout to delay 2 seconds, then update user.name and loading.value.

4
Add template to show loading and user name
Add a <template> section that shows Loading... text when loading.value is true, and shows User: {{ user.name }} when loading.value is false.
Vue
Need a hint?

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