Add Loading Indicator In Vue JS

Introduction:

User experience (UX) loading indicators are beneficial for both web and mobile applications. These animations let the user know when an action is being taken and when the outcome will appear.

There are two main events in web applications that require loaders:

  • AJAX requests and page navigation are examples of network requests.
  • When a complex computation is active.

Several methods for including loaders in your Vue.js apps will be covered in this post.

Get Started:

Step 1:

Set up a new project using this CLI.

vue create loading-indicators

Then go to your main directory of projects.

cd loading-indicators

Step 2: Use nprogress for the loading indicator.

You are free to use any loading indicator you like. You will set up nprogress as your loading indicator for this tutorial.

Npm or yarn won’t be used for this. You will use a CDN to reference it (content delivery network).

Navigate to the public/index.html file in the newly established Vue CLI project:

Add this code in the <head> section.

//
//
<link href="https://unpkg.com/nprogress@0.2.0/nprogress.css" rel="stylesheet" /> 
<script src="https://unpkg.com/nprogress@0.2.0/nprogress.js"></script>

There are a few API methods that nprogress provides, but for this post, you only need two: start and done. These procedures kick off and end the progress bar.

The progress of the loader can also be modified using nprogress. This can be manually modified, however, for the sake of this article, the default behavior will be used.

Step 3: Add a router to your project by this CLI.

vue add router

After running this CLI, you can see your structure as below.

Now open router/index.js file and add this code before export default.

router.beforeResolve((to, from, next) => { 
  // If this isn't an initial page load. 
  if (to.name) { 
    // Start the route progress bar. 
    NProgress.start() 
  } 
  next() 
}) 

router.afterEach((to, from) => { 
  // Complete the animation of the route progress bar. 
  NProgress.done() 
})

Finally, run your project and you can see the loading indicator at the top of the project when you route from one URL to another URL.

npm run serve

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories