Single Page Applications Chapter 15
How to do it...
As stated earlier, I will assume that you have all the code resulting from the Fetching data
before switching route recipe in place and working.
For this recipe, we will use an additional dependency--NProgress, a small utility to
display a loading bar on top of the screen.
Add the following two lines inside the head of your page or the list of dependencies in
JSFiddle (there is also a package for npm):
<link rel="stylesheet"
href="https://cdn.bootcss.com/nprogress/X/nprogress.css">
<script src="https://cdn.bootcss.com/nprogress/X/nprogress.js"></script>
Here, X is the version of NProgress. At writing time it was 0.2.0, but you can look it up
online.
After we've done this, the next step is to define the behavior we want from the progress bar.
First, we'd like the progress bar to appear as soon as we click on the link. For this, we can
add an event listener to the click event, but it will be a poor design if we had, say, a
hundred links. A much more sustainable and clean way to do it is by creating a new hook
for the router and connecting the appearance of the progress bar with the switching of the
route. This will also have the advantage of offering a consistent experience throughout the
application:
router.beforeEach((to, from, next) => {
NProgress.start()
next()
})
In a similar fashion, we want the bar to disappear when loading is completed successfully.
This means that we want to do it inside the callback:
beforeRouteEnter (to, from, next) {
axios.post('http://schematic-ipsum.herokuapp.com/', {
"type": "object",
"properties": {
"name": {
"type": "string",
"ipsum": "name"
},
"phone": {
"type": "string",
"format": "phone"