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
Importing the files
once the installation is complete we can move on to adding the code to 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 have an 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 a 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();
}
});