Show loader on AJAX – VueJS

Today, you will learn, how you can show a loader in VueJS when an AJAX is called. We will be using Axios library for calling AJAX request.

If you do not want to use Axios library, you can use the default XMLHttpRequest object of Javascript. Learn how to do it from here.

Video tutorial:

Let’s say we have the following code that:

  1. Includes VueJS and Axios library.
  2. Create a div for Vue app.
  3. Mount Vue app onto the div.
  4. On mounted, calls an AJAX request.
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<div id="app"></div>

And following javascript code will mount the Vue app.

Vue.createApp({
	async mounted() {
		const response = await axios.post(
			"https://api.github.com/users/adnanafzal565"
		)
		
		console.log(response)
	}
}).mount("#app")

Now, I will create a loading text that will be displayed only if the loading variable is true.

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<div id="app">
	<p v-if="loading">Loading...</p>
</div>

Then I will create that variable in my Vue app and initialize it as false.

Vue.createApp({

	data() {
		return {
			loading: false
		}
	},

	async mounted() {
		const response = await axios.post(
			"https://api.github.com/users/adnanafzal565"
		)
		
		console.log(response)
	}
}).mount("#app")

Lastly, we are going to set this variable to true before calling the AJAX and false after the AJAX is finished.

Vue.createApp({

	data() {
		return {
			loading: false
		}
	},

	async mounted() {
		this.loading = true
		
		const response = await axios.post(
			"https://api.github.com/users/adnanafzal565"
		)
		
		this.loading = false
		
		console.log(response)
	}
}).mount("#app")

So that’s it. That’s how you can show a loader while AJAX is being called in VueJS.