This code snippet demonstrates how to display a loading indicator in a Vue application when fetching data.
It leverages Vue’s v-if
directive to conditionally render a loading spinner based on the state of the data fetch operation.
In the snippet below, we have our data property loading
which is set to false
by default.
Before we start fetching our data, we set loading
to true
and when we get a response from the server, we set it back to false
.
Code Snippet
<template>
<main>
<div v-if="loading" class="loader"></div>
<div>{{ todo }}</div>
</main>
</template>
<script>
export default {
data() {
return {
loading: false,
todo: ''
};
},
async created () {
this.loading = true
try {
const res = await fetch('https://jsonplaceholder.typicode.com/todos/1')
this.todo = await res.json()
this.loading = false
} catch (error) {
console.log(error)
this.loading = false
}
}
};
</script>
<style lang="scss" scoped>
.loader {
border: 16px solid #f3f3f3;
border-top: 16px solid #3498db;
border-radius: 50%;
width: 36px;
height: 36px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
Explanation
This Vue component contains a data property ‘loading’ which is initially set to false. As we start the data fetching operation, ‘loading’ is set to true. When the response from the server is received, loading
is set back to false.
In the template section, the v-if
directive is used to conditionally render the loader div based on the ‘loading’ state. If loading
is true, the spinner is displayed, otherwise, it’s hidden.
Use Cases
- Fetching a list of users
- Fetching an image/video
Example
You can use this technique when you’re fetching a list of users, an image, a video, or any other data from a server.
The loading spinner will be shown while the data is being fetched, providing feedback to the user that an operation is in progress.
Conclusion
Using Vue.js’s v-if
directive along with a loading state variable is a simple and effective way to display a loading indicator during data fetch operations.
It provides a better user experience by giving visual feedback during the loading process. The same technique can be used with other types of loading indicators, such as progress bars.