Sometimes, we want to show a loading spinner in our Vue app to indicate the app is loading.
In this article, we’ll look at how to add a loading spinner to a Vue app with the Vue Loading Overlay component.
Installation
To install the package, we can run:
npm i vue-loading-overlay
with NPM.
Usage
Once we installed it, we can use it by writing:
<template>
<div>
<loading
:active.sync="isLoading"
:can-cancel="true"
:on-cancel="onCancel"
:is-full-page="fullPage"
>
</loading>
<button @click.prevent="doAjax">fetch Data</button>
</div>
</template>
<script>
import Loading from "vue-loading-overlay";
import "vue-loading-overlay/dist/vue-loading.css";
export default {
data() {
return {
isLoading: false,
fullPage: true,
};
},
components: {
Loading,
},
methods: {
doAjax() {
this.isLoading = true;
setTimeout(() => {
this.isLoading = false;
}, 5000);
},
onCancel() {
console.log("User cancelled the loader.");
},
},
};
</script>
We import the Loading
component and register it in the components
property.
Also, we import the CSS file to add the spinner styles.
Then we add the loading
component into the template.
active
is set to the condition when the spinner shows.
can-cancel
set to true
means we can close the spinner manually.
on-cancel
is a function that runs when the spinner closes.
is-full-page
is set the condition when the spinner will take the full page.
In the methods
property object, we add the doAjax
method to set this.isLoading
to control when the spinner shows.
onCancel
is the method we run when we close the spinner.
We can also use the library as a plugin.
For instance, we can write:
<template>
<form @submit.prevent="submit" style="height: 500px" ref="formContainer">
<button type="submit">Login</button>
</form>
</template>
<script>
import Vue from "vue";
import Loading from "vue-loading-overlay";
import "vue-loading-overlay/dist/vue-loading.css";
Vue.use(Loading);
export default {
data() {
return {
fullPage: false,
};
},
methods: {
submit() {
const loader = this.$loading.show({
container: this.$refs.formContainer,
canCancel: true,
onCancel: this.onCancel,
});
setTimeout(() => {
loader.hide();
}, 5000);
},
onCancel() {
console.log("User cancelled the loader.");
},
},
};
</script>
We have the form with a ref assigned to it.
The form element will be used as the container for the spinner.
Then we import the modules and CSS in the same way.
Next, we call Vue.use
to register the plugin.
Then we have the submit
method that calls this.$loading.show
to show the loading spinner,
container
is set to the form element which is stored in this.$refs.formContainer
.
canCancel
sets whether we can close the spinner or not.
onCancel
is set to the method that we want to run when we close the spinner.
So when we click Login, we see the spinner displayed for 5 seconds or until we click on it.
Conclusion
We can add a loading spinner into our Vue app with Vue Loading Overlay.