DEV Community

loading...
Cover image for Adding a route loading bar to Vue and Gridsome
Developer Bacon 🥓🥓

Adding a route loading bar to Vue and Gridsome

brettanda profile image Brett Anda 🔥🧠 Originally published at developerbacon.ca on ・2 min read

Dependency Installation

For this tutorial, I have decided to use NProgress for the loading indicator. You can check the demo page at ricostacruz.com/nprogress.

To start this tutorial you will need to install NProgress.

npm install nprogress
#or
yarn add nprogress
Enter fullscreen mode Exit fullscreen mode

Importing the files

once the installation is complete we can move on adding the code the main.js file. If you don't already have one it should be located in src/main.js. To start using NProgress we will have to import the JavaScript and CSS.

import NProgress from "nprogress";
import "nprogress/nprogress.css";
Enter fullscreen mode Exit fullscreen mode

If you a SCSS file that you would rather import the CSS there you will need something like this. This import will look different depending on your setup and where your SCSS file is located.

@import "../../../node_modules/nprogress/nprogress.css";
Enter fullscreen mode Exit fullscreen mode

Now for the actual code

Your main.js files should look something like this. Note that the function is grabbing the router object. I added the typeof document !== "undefined" to the if statement because of an error I received during build.

export default function(Vue, { router }) {
    router.beforeEach((to, from, next) => {
        if (!to.hash && typeof document !== "undefined") {
            NProgress.start();
        }
        next();
    });

    router.afterEach((to, from) => {
        if (!to.hash && typeof document !== "undefined") {
            NProgress.done();
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

If you are not using Gridsome this is the documentation for router gaurds for Vue and your main Javascript file where your router is defined should look something like this:

const router = new VueRouter({ ... });

router.beforeEach((to, from, next) => {
  if (!to.hash) {
    NProgress.start();
  }
  next();
});

router.afterEach((to, from) => {
  if(!to.hash) {
    NProgress.done();
  }
});
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

pic
Editor guide
Collapse
slemonade profile image
Ciaran

Worked for me! I copied nprogress/nprogress.css to my own custom CSS file and styled it from there instead.