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

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";

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";

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();
        }
    });
}

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();
  }
});

Posted on by:

brettanda profile

Brett Anda 🔥🧠

@brettanda

I make tutorials for beginner developers at developerbacon.ca 🥓

Developer Bacon 🥓🥓

A website made with Gridsome aimed to help beginner web developers

Discussion

markdown guide