Categories
JavaScript Vue

Add a Spinner to Our Vue app with the vue-spinners Package

Spread the love

The vue-spinners package is very useful for adding a loading spinner into our Vue app.

It’s very easy to use.

We just have to install the package by running:

npm install --save @saeris/vue-spinners

or

yarn add @saeris/vue-spinners

Then we can register the package by adding the following to main.js:

import Vue from "vue";
import App from "./App.vue";
import { VueSpinners } from "@saeris/vue-spinners";

Vue.use(VueSpinners);

Vue.config.productionTip = false;
new Vue({
  render: h => h(App)
}).$mount("#app");

Then in App.vue, we write:

<template>
  <div id="app">
    <ClipLoader :loading="loading" color="#bada55" :size="150" sizeUnit="px"/>
  </div>
</template>

<script>
export default {
  name: "App",
  data(){
    return {
      loading: true
    }
  },
  created() {
    this.loading = true;
  },
  mounted() {
    setTimeout(() => {
      this.loading = false;
    }, 5000);
  }
};
</script>

We have the ClipLoader component on our template.

We set the color prop to set the color of the spinner.

sizeUnit is set to px for pixels.

size is set to 150, so the spinner is set to 150px big.

We have the loading state which is set to the value of the loading prop to set when the spinner will be shown.

Then in the created hook, which loads before the mounted, we set this.loading to true so that the spinner will show.

Then in mounted we use setTimeout to set this.loading to false after 5 seconds.

This will unload the spinner after 5 seconds.

Now we get a green spinner that displays for 5 seconds when the component loads.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.