Create a unique custom spinning loader for a straightforward Vue.js application

I've set up a basic Vue project on codesandbox.io that includes vue-router and a custom spinner for loading.

Spinner.vue:

<template>
  <div class="spinner" v-show="loading">
    <span class="sync" v-bind:style="[spinnerStyle, spinnerDelay1]"></span>
    <span class="sync" v-bind:style="[spinnerStyle, spinnerDelay2]"></span>
    <span class="sync" v-bind:style="[spinnerStyle, spinnerDelay3]"></span>
  </div>
</template>
<script>
export default {
  name: "Spinner",
  props: {
    loading: {
      type: Boolean,
      default: true
    },
    color: {
      type: String,
      default: "#5dc596"
    },
    size: {
      type: String,
      default: "15px"
    },
    margin: {
      type: String,
      default: "2px"
    },
    radius: {
      type: String,
      default: "100%"
    }
  },
  data() {
    return {
      spinnerStyle: {
        backgroundColor: this.color,
        height: this.size,
            width: this.size,
        borderRadius: this.radius,
        margin: this.margin,
        display: 'inline-block',
        animationName: 'spinerAnimation',
        animationDuration: '1.25s',
        animationIterationCount: 'infinite',
        animationTimingFunction: 'ease-in-out',
        animationFillMode: 'both'
      },
      spinnerDelay1: {
        animationDelay: '0.07s'
      },
      spinnerDelay2: {
        animationDelay: '0.14s'
      },
      spinnerDelay3: {
        animationDelay: '0.21s'
      }
    };
  },
  methods: {
    start() {
      this.loading = true;
    },
    end() {
      this.loading = false;
    }
  }
};

</script>

The main page is called Home.vue and it contains links to other components:

 <router-link to="/">Home</router-link>
 <router-link to="/helloworld">Hello World</router-link>
 <router-link to="/bigimg">Big Img</router-link>

Additionally, there's the main.js file:

import Vue from "vue";
import App from "./App";
import router from "./router";

import Spinner from "./components/Spinner";

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: "#app",
  router,
  components: {
    App,
    Spinner
  },
  template: "<App/>"
});

router.beforeEach((to, from, next) => {
  console.log("next page");
  //loading = true
  next();
});

router.afterEach((to, from) => {
  //setTimeout(() => (loading = false), 1500);
});

I want the Spinner Loader to activate when the main page (Home.vue) loads, as well as when navigating to other pages within the project.

Question: How can I trigger the loader to be displayed when loading the main page (Home) and also when navigating to other pages of the project?

Answer №1

To start, create a state variable:

const status = {
    active: false
};

Add it to your main.js file:

new Vue({
  ...
  data: {
    status
  },
});

Include a condition in your main template:

new Vue({
  ...
  template: '<App v-if="!status.active" /><Loader v-else/>'
});

Update the state before each route change:

router.beforeEach((to, from, next) => {
  console.log("Moving to the next page");
  status.active = true;
  setTimeout(() => {
    status.active = false;
  }, 3000);
  next();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

While iterating through the material-ui rating component, the 'index' value remains constant at 0 within the 'onChange' function

For my e-commerce React.js web app, I want to show the rating value of each product. Using the JS map function, I was able to track which product was hovered by its index ('onChangeActive' is the handler for this). {products.map((product, index) ...

Ways to extract a value from an HTML form in ASP.NET when using Html.EnumDropDownListFor

I am a beginner in ASP.NET and I recently set up a form that allows input from a C# enum: <form method="get"> <div class="form-group"> <label>Select Type:</label> @Html.EnumDropDownListFor(x = ...

The use of jQuery ajax requests is leading to a refresh of the page

I've encountered an issue with a button on my HTML page that is not associated with any form. <input type='button' id='submitter' value='add'/> There is a click handler attached to it: $('#submitter').c ...

The Angular $http.jsonp() function can only be executed one time

Upon the first response being successful (alert->done), any subsequent hits will result in an 'error' response. I attempted to resolve this issue by adding some config parameters with 'cache: false', but it still only works the firs ...

What is the best way to simultaneously utilize two APIs where one is using HTTP and the other is using HTTPS?

What is the best way to simultaneously use two APIs, one being http and the other https, in Angular or JavaScript? ...

Once the image is loaded, cropped, and displayed on the canvas, what is the best way to implement image rotation functionality for the user before converting it to base64?

My process involves cropping images to a square shape and drawing them onto a canvas. if(img.height >= img.width) { ctx.drawImage(img, 0, 0, 110, 110 * img.height / img.width); } else { ctx.drawImage(img, 0 , 0, 110 * img.width ...

Encountering an issue with CORS while running a node application on a local server

I am facing a challenge where I want to send POST data from a JavaScript script to a node server application using express. However, when I attempt to send the data, I encounter an error stating: CORS-Header 'Access-Control-Allow-Origin' does not ...

Waiting for the API endpoint to be posted on the development tool

After creating login credentials in the database, I am facing an issue when trying to use them to log in. The network response for the /api/login endpoint remains stuck on a pending request. Upon checking the response, it seems that the payload data intend ...

What are some ways to divide drop targets with React DnD?

In my React Dnd v16.0.1 project, I am dynamically rendering containers and images from JSON data using map function. The issue I'm facing is with two droppable containers where only one should accept dropped images. However, when I drop an image on th ...

What is the best way to download the entire NPM repository to maximize offline development pleasure?

During a recent vacation, I faced the frustrating challenge of limited internet access while developing an application in node.js. The need for certain NPM packages caused a major setback in my progress as I had to wait until I could go online to download ...

Problem with Vue Router in Laravel subroute leading to incorrect component discovery

While I had a similar setup working smoothly on another Laravel/Vue project with the main route /, I encountered an issue when grouping the Vue instance under an admin subroute. All paths entered after "admin" would redirect to a PageNotFound component tha ...

encase a function with javascript

let myString = "I am creating a program."; //function to calculate number of letters const letterCount = (str) => str.length; //function to calculate number of words const wordCount = (str) => str.split(" ").length; //function ...

Disappearing Data: Struts2 Autocompleter's Entries Vanishing Upon Submit Button Click

I am currently utilizing the auto-complete feature from The issue I am facing is that when I type "Ball", the auto-complete suggests "Balloon". Even though both "Balloon" and "Balloon" appear in the text field and the list, when I click elsewhere on the s ...

ways to display a chosen option in a dropdown menu

Below is the code snippet I am currently using, which involves JQuery and Bootstrap 4: $('.dropdown-menu li').on('click', function() { var selectedValue = $(this).text(); $('.dropdown-select').text(selectedValue); }); & ...

Having trouble with the installation of Parcel bundler via npm

Issue encountered while trying to install Parcel bundler for my React project using npm package manager. The terminal displayed a warning/error message during the command npm i parcel-bundler: npm WARN deprecated [email protected]: core-js@<3 is ...

Combining Angular 2 and Symfony 3 for seamless integration

I am currently working on integrating Angular 2 with Symfony 3. After using npm to install node modules, I encountered an issue linking them from my base view base.html.twig. Despite adding scripts, none of them seem to be working or appearing in the page& ...

Has Angular been assimilated into the window object by webpack?

I'm encountering a puzzling issue with webpack that I can't seem to resolve. Here is the link to my webpack.config file: https://github.com/saike/maluvich-browser/blob/master/webpack.config.babel.js In my project, I import angular using ES6 mo ...

Is the alert still displayed during a frozen UI, even when it is within a synchronous ajax call?

Here is the code snippet for implementing global AJAX functionality. jQuery(function (){ $(document).ajaxStop(function() { alert("stop"); }); $(document).ajaxStart(function() { al ...

Bootstrap4 does not support the <button> element

How can I achieve a 'collapse icon' floated to the left followed by Copyright © using Bootstrap 4? I've looked at similar questions on this topic, but none seem to provide a direct answer. Other questions contain different code with ob ...

The POST method in Node JS request-promises does not properly handle string inputs

When I am trying to establish a connection between my node.js module and another server, I utilize the 'request-promise' library. My implementation for posting data looks like this: rp.({ method: 'POST', headers:{ 'Conte ...