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();
}
});
Top comments (2)
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.
Worked for me! I copied
nprogress/nprogress.css
to my own custom CSS file and styled it from there instead.