How to Handle Loading State in Vue: Simple and Effective Approach
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.
<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>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.
<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>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
loadingstate 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
loading variable to track async operation status in Vue.v-if or v-show based on loading state.loading to true before fetching and false after completion.