I aim to conceal the Spinner feature within the service layer of Vue JS

I have a basic bootstrap Spinner.vue component

<template>
    <div class="modal" v-if="start">
          <div class="spinner-border text-info" role="status" style="width: 3rem; height: 3rem;">
            <span class="visually-hidden">Loading...</span>
          </div>
    </div>
</template>

<script>
export default {
    name: 'Spinner',
    props: {
        start: {
            type: Boolean,
            default: true,
        },
    },
}
</script>

Considering the scale of my application, it might not be efficient to import this component into every component or page where a spinner is needed for data fetching. I also would like to prefetch data and pass it directly to a page using Vue Router like shown below:

const routes = [
  {
    name: RouteNames.XYZ,
    path: '/xyz',
    beforeEnter: async (to) => {
      let data = await Service.getList();
      to.params.list= data.list;
    },
    component: xyzList,
  },
]

It would be advantageous if my service wrapper class had methods to showSpinner and hideSpinner that can be used in all data-fetching methods such as Service.getList(). Is there a way to achieve this? Can I somehow incorporate my Spinner component into this JavaScript service class?

If possible, I would prefer to implement this functionality without relying on an external spinner library."

Answer №1

If you want to streamline this process, consider integrating this component into the App.vue file. By doing so, it will be readily available when the application loads.

Do you happen to have request interceptors set up for your data fetching (possibly using Axios)?

Within these interceptors, you can manage the spinner's visibility. With a bit more insight into your code, I could offer additional assistance in guiding you further.

Below is a basic illustration. Notice that the store has been imported, allowing you to utilize it to initiate a mutation with commit and toggle the spinner display.

import axios from "axios";
import store from "../store";

const Axios = axios.create({
    baseURL: process.env.VUE_APP_BASE_API_URL,
});

const addToken = (config: any) => {
    const token = store.getters["Auth/getToken"];
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
};

Axios.interceptors.request.use(
    (config) => {
        // activate the spinner functionality here
        addToken(config);
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

Axios.interceptors.response.use(
    (response) => {
        // deactivate the spinner functionality here
        return response
    },
    (error) => Promise.reject(error)
);

export default Axios;

Your routing configuration should not impact the desired outcome of this implementation.

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

python extract values from a JSON object

I've been searching everywhere, but I haven't been able to find a solution. It seems like my question is not clear enough, so I'm hoping to receive some guidance. Currently, I am working with turbogears2.2. In my client view, I am sending a ...

The functionality of Jquery appears to be malfunctioning on the Drupal platform, although it performs

I've built a jQuery carousel that is fully functional when tested locally, but encounters issues when uploaded to a Drupal platform. Surprisingly, the jQuery functions properly when entered through the Console. Here's the jQuery code: carousel = ...

There seems to be a disconnect between the React Redux store

When attempting to connect my store to a React application, I encountered the following error: TypeError: state is undefined store/index.js (Creating Reducer function) import {createStore} from 'redux'; const counterReducer = (state:{counter:0} ...

An error occurred while attempting to reset your password on Parse.com (JS SDK) due to an

I am having trouble resetting my password in my angularjs App. I am utilizing Parse (js SDK) as the backend. Even though I am following the documentation and using Parse.User.requestPasswordReset, I keep encountering error 125 which states invalid email ad ...

Exploring the documentation of node.js with doxygen

When it comes to my C projects, I make sure to document them using Doxygen. Recently, I delved into the world of NodeJs and attempted to document .js files with Doxygen, but unfortunately, no output was generated. Despite my efforts to search for answers ...

The jQuery AJAX function appears to be unresponsive and failing to execute

I have a form that needs to update values on click of a radio button. Unfortunately, my jQuery skills are lacking. Here's what I have tried so far: HTML: <form> <input type="radio" checked="true" id="q1r1" name="q1" value="Awesome"> ...

What could be causing the delay in this script's execution?

I'm attempting to include a script at the beginning of my XBL file, however even the test below is not functioning. Any insight on why this might be happening? <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xbl="http://www.mozilla.org/x ...

What strategies can be implemented to decrease the initial loading duration of a YouTube iframe video?

What are some techniques we can use to decrease iframe loading time? Is it possible to implement lazy loading for YouTube iframe videos? I experimented with initially hiding the iframe and displaying an image instead. However, when the user clicks, it req ...

What could be causing the Quasar drawer to overlap the Quasar toolbar in a Vue application?

I am currently utilizing the quasar UI framework and have a main layout file that includes only a toolbar. This toolbar is meant to display across all pages in my application. <template> <q-layout view="hHh Lpr lff" style="backgro ...

Error encountered at / - undefined local variable or method `parameters' for main:Object (Executing Stripe Charge with Stripe.js)

Encountering an error with the code below while attempting to create a Stripe charge using Stripe.js. Below is my web.rb file: require 'json' require 'sinatra' require 'sinatra/reloader' require 'stripe' get &a ...

The variables $invalid and $valid in my AngularJS form have not been assigned any values

I came across a post on StackOverflow discussing the issue of both "myForm.$valid" and "myForm.$invalid" being undefined on an Angular form. However, my problem is slightly different. I have defined a form like this: <form name="EntityForm" role="form ...

Having difficulty resolving all parameters for the component: (?, [object Object]) in the Jasmine component Unit Test

While defining a UT for a component with an extended class using i8nService and ChangeDetectionRef, I encountered an error preventing me from instantiating it: Failed: Can't resolve all parameters for BrandingMultiselectComponent: (?, [object Object] ...

The jQuery menu is malfunctioning in Internet Explorer due to the Document Mode being set to Quirks

I am encountering an issue where the below code is not functioning properly in Internet Explorer's document mode quirks. Each time I hover over the submenu, its length doubles unexpectedly. Can someone please provide assistance with this matter? < ...

JQuery is facing difficulty in animating a div following the completion of a "forwards" css animation

Check out this example: http://jsfiddle.net/nxsv5dgw/ A div appears on the stage and a CSS animation is applied to it. However, when attempting to use JQuery to animate the same properties that were animated by CSS, it seems to no longer work properly. ...

What is the process for obtaining a client-side cookie using next.js?

I'm currently facing an issue where I can't seem to maintain a constant value for the isAuthenticated variable between server-side and client-side in next.js. In my setup, I am using a custom app.js file to wrap the app with Apollo Provider. The ...

Using Vue.js for redirecting with a post method

Is there a way to redirect from Vue.js to a Laravel controller using the POST method without using AJAX? I would like to be able to use var_dump or dd inside the controller. //Vue.js axios.post('/add-hotel-listing', this.finish).then((respons ...

An error in TypeScript has occurred, stating that the type 'IterableIterator<any>' is neither an array type nor a string type

Hey there! I'm currently working on an Angular project and encountering an error in my VS Code. I'm a bit stuck on how to fix it. Type 'IterableIterator<any>' is not an array type or a string type. Use compiler option '- ...

Is there a way to retrieve the client's IP address from the server side within a Next.js application?

How can I determine the user's time zone and location in order to generate a server-side page tailored to their specific location and time zone? I am struggling to retrieve the user's IP address from the request or the localhost IP address (127.0 ...

Issues with AJAX junk appearing after the document element in Firefox are causing disruption

Currently, I am utilizing a page fetch script to dynamically insert a web page into a div element on my site. Let's take a look at the code. By the way, I am running this on Firefox with Kubuntu. function fetchContent(URL, divId) { req = wind ...

Learn how to efficiently send multiple image files to the server by utilizing Formidable and React JS

I am encountering an issue while attempting to upload five images to the server. The code file is provided below, and any assistance would be greatly appreciated. In this scenario, I am inputting image files and storing them in an array, but Formidable in ...