0
0
VueDebug / FixBeginner · 4 min read

How to Handle Loading State in Vue: Simple and Effective Approach

In Vue, handle loading state by creating a reactive loading variable and toggling it during async operations. Use v-if or v-show in the template to display loading indicators while data is fetching.
🔍

Why This Happens

When you fetch data asynchronously in Vue without managing a loading state, the UI may show empty or incomplete content, confusing users. This happens because Vue renders before the data arrives, and no indication is given that loading is in progress.

vue
<template>
  <div>
    <p>Data: {{ data }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const data = ref(null)

onMounted(async () => {
  const response = await fetch('https://api.example.com/data')
  data.value = await response.json()
})
</script>
Output
Data:
🔧

The Fix

Introduce a loading reactive variable set to true before the async call and false after data loads. Use v-if to show a loading message or spinner while loading is true, and show data only when loading is false.

vue
<template>
  <div>
    <p v-if="loading">Loading data...</p>
    <p v-else>Data: {{ data }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const data = ref(null)
const loading = ref(true)

onMounted(async () => {
  const response = await fetch('https://api.example.com/data')
  data.value = await response.json()
  loading.value = false
})
</script>
Output
Loading data... (while fetching), then Data: {fetched data}
🛡️

Prevention

Always initialize a loading state when performing async operations in Vue. Use clear and user-friendly loading indicators. Consider reusable loading components and handle errors gracefully to improve user experience.

Use Vue DevTools to inspect reactive states and ensure loading toggles correctly. Follow consistent naming like loading or isLoading for clarity.

⚠️

Related Errors

Common related issues include:

  • Not resetting loading state on repeated fetches causing stale UI.
  • Showing data before it is ready, leading to empty or broken UI.
  • Not handling fetch errors, leaving loading spinner forever.

Fix these by resetting loading properly and adding error handling with try/catch.

Key Takeaways

Use a reactive loading variable to track async operation status in Vue.
Toggle UI elements with v-if or v-show based on loading state.
Always set loading to true before fetching and false after completion.
Add user-friendly loading indicators to improve user experience.
Handle errors to avoid infinite loading states.