Display Loader in Vue JS while making Ajax request

Posted by

Showing Loader on Ajax in Vue JS

Show Loader on Ajax in Vue JS

In Vue JS, when making AJAX requests, it’s important to provide visual feedback to the user that something is happening in the background. One way to do this is by showing a loader or spinner while the request is being made.

Here’s a simple example of how you can show a loader on AJAX requests in Vue JS:

First, you’ll need to include a loader/spinner in your HTML markup. You can use a library like Font Awesome to include a spinner icon:


<i class="fas fa-spinner fa-spin"></i>

Now, in your Vue JS component, you can use a data property to control the visibility of the loader. For example:


<template>
<div>
<div v-if="isLoading" class="loader">
<i class="fas fa-spinner fa-spin"></i>
</div>
<button @click="makeAjaxRequest">Make AJAX Request</button>
</div>
</template>

<script>
export default {
data() {
return {
isLoading: false
}
},
methods: {
makeAjaxRequest() {
this.isLoading = true;
// Make your AJAX request here
// Once the request is complete, set isLoading back to false
}
}
}
</script>

In this example, we have a button that triggers an AJAX request when clicked. Before making the request, we set isLoading to true, which makes the loader visible. Once the request is complete, we set isLoading back to false, hiding the loader.

By incorporating a loader/spinner into your AJAX requests, you can provide a better user experience and improve the overall feel of your Vue JS application.

.loader {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}