Categories
JavaScript Vue

Add a Progress Bar to a Vue App with vue-progress-bar

Spread the love

We can add a progress bar to a Vue app with the vue-progress-bar package.

To get started, we install the package by running:

npm install vue-progressbar

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

import Vue from "vue";
import App from "./App.vue";
import VueProgressBar from "vue-progressbar";

const options = {
  color: "#bffaf3",
  failedColor: "#874b4b",
  thickness: "5px",
  transition: {
    speed: "0.2s",
    opacity: "0.6s",
    termination: 300
  },
  autoRevert: true,
  location: "left",
  inverse: false
};

Vue.use(VueProgressBar, options);

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

We called Vue.use with VueProgressBar and an object with some options to style the progress bar.

Then in App.vue, we add:

<template>
  <div id="app">
    <vue-progress-bar></vue-progress-bar>
  </div>
</template>

<script>
export default {
  name: "App",
  mounted () {
    this.$Progress.finish()
  },
  created () {
    this.$Progress.start()
    this.$router.beforeEach((to, from, next) => {
      if (to.meta.progress !== undefined) {
        let meta = to.meta.progress
        this.$Progress.parseMeta(meta)
      }
      this.$Progress.start()
      next()
    })
    this.$router.afterEach((to, from) => {
      this.$Progress.finish()
    })
  }
};
</script>

We add call this.$Progress.start() to display the progress bar.

Then we called this.$Progress.finish() to remove the progress bar from view.

Also, we have the $this.$router.beforeEach call to show the progress bar when navigation begins and call $this.$progress.finish() when navigation is done.

Now we can see a progress bar on the left side of the screen when the component or routes load.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *