DEV Community

Cover image for Adding a route loading bar to Vue and Gridsome
Brett Anda 🔥🧠 for Developer Bacon 🥓🥓

Posted on • Originally published at developerbacon.ca on

Adding a route loading bar to Vue and Gridsome

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

Top comments (2)

Collapse
 
nitras profile image
nitras

Thanks for your tutorial. I can see the progressbar but I do not have the feeling that it actually preloads the content and then shows it?

What i can see is the fact that the content is on the page and simulatiosly the progress bar runs. Not sure how to configure this whole thing to ensure the page is empty, progress is loading and then show the page.

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.