Showcasing a visual loading sequence while a Vue.js operation is in progress

An issue arises with the simple show and hide functionality on the loading element while executing a Vue js function.

The Vue js function is designed to perform certain tasks and update data upon completion. In an attempt to display a loading animation during this process, I have simplified the process by using a basic loop for discussion purposes, eliminating other potential issues such as ajax or async operations.

Here is the HTML code for the button:

<button type="button" v-on:click="DoStuff()">Do Stuff</button>

And here is the corresponding vue js code:

var client = new Vue({
    el: '#client',
    data: {
        someData: []
},
methods: {
    DoStuff: function() {

        //Show Loader
        $(".loader").show();

        //Simulate delay 
        for (var i = 0; i < 100000000; i++) {
            var x = i;
        }

        //Hide loader
        $(".loader").hide();

        // Notify user when done.
        alert('Task complete');
    }

However, the loader fails to appear. If I disable the hide command, the loader appears only after the alert, indicating a possible underlying asynchronous operation despite not intentionally implementing any async procedures.

Answer №1

Why rely on jQuery to show and hide elements based on conditions when VueJS and similar front-end frameworks can handle this task more efficiently?

To start, include a loading property in your data object:

data: {
   someData: [],
   loading: false
}

Next, in your doStuff function, eliminate the jQuery code and update the loading property accordingly:

methods: {
    doStuff: function() {
        //Display Loader
        this.loading = true;

        //Simulate 5-second delay
        setTimeout(() => {
           this.loading = false;
        }, 5000)
    }
}

Lastly, in your view, add this line:

<div v-if="loading">Loading data</div>

I'd also like to point out that your snippet seems slightly off. The methods property should be inside the Vue instance definition.

var client = new Vue({
    el: '#client',
    data: {
        someData: [],
        loading: false
    },
    methods: {
       doStuff: function() {
          //Display Loader
          this.loading = true;

          //Simulate 5-second delay
          setTimeout(() => {
            this.loading = false;
          }, 5000)
       }

   }
}

Answer №2

Avoid using jquery in this situation, as you can achieve the desired functionality with vuejs.


var app = new Vue({
    el: '#app',
    data: {
        myData: [],
        showLoader: false,
},
methods: {
    HandleAction() {

        //Display Loader
        this.showLoader = true;

        //Simulate 5 seconds delay

        //Hide loader after processing
        this.showLoader = false;

        // Let the user know it's completed.
        alert('Done');
    }

Here is your corresponding HTML code snippet.

<div class="loader" v-if="showLoader">
    Loading....
</div>
<div v-else>
Content of your webpage 
</div>

Answer №3

Avoid using JQuery and opt for Vue conditional displaying with v-show instead.

When creating your loader:

<div class="loader" v-show="loading"></div>

Incorporate the following Vue code:

var app = new Vue({
    el: '#app',
    data: {
        dataItems: [],
        loading: false
},
methods: {
    PerformAction: function() {

        this.loading = true;

        //Simulate a delay of 5 seconds
        for (var i = 0; i < 100000000; i++) {
            var x = i;
        }

        this.loading = false;

        // Display a message indicating completion
        alert('Task completed');
    }

Answer №4

Appreciate everyone's input. Currently, I need to shift my focus to addressing a more pressing feature that has arisen. However, I still wanted to share the insights I've gathered so far. While this may not be the ultimate solution, it certainly sheds light on the issue and suggests the correct approach.

Andrew Lohr accurately pinpointed the problem, which is elaborated further in this thread: jQuery hide() and show() not immediately run when reversed later in the function

One possible solution, among others, involves utilizing an event bus, as suggested by perellorodrigo in this resource: https://flaviocopes.com/vue-components-communication/

I will share my final resolution once I have had the opportunity to work on it.

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

leveraging Ajax to submit a segment of the webpage

-Modified- Greetings, I am facing a situation where I need to post only the second form on a page that contains two forms. The second form has a function for validating data such as date, email, etc. My goal is to send the second form without reloading ...

Having difficulty adjusting the height and color of vuetify's card and navigation drawer

I'm struggling to adjust the height of the vuetify card to match the size of the browser window and also trying to change its color. Even after copying the example code provided by Vuetify, as shown below: <template> <v-card class=&quo ...

Refresh the div by updating it with the outcome of an Ajax request

How can I show the result of the ajax function below in a div on the webpage (specifically, update div)? I am looking for a solution that does not require using bulky plugins. url: 'http://dowmian.com/xs1/getcam.php', type: 'GET', data ...

Creating a multi-dimensional array in order to store multiple sets of data

To generate a multidimensional array similar to the example below: var serviceCoors = [ [50, 40], [50, 50], [50, 60], ]; We have elements with latitude and longitude data: <div data-latitude="10" data-longitude="20" clas ...

Firestore's get document method may cause an unmounted warning

I've been working on a React.js project that integrates with Firestore, and I ran into an issue where using the get method for fetching documents resulted in a "Can't perform a React state update on an unmounted component" warning. However, when ...

Changing the location or filename of the .env file in Nuxt: A comprehensive guide

I'm looking for a way to customize the location and name of my environment variable file (.env) in my Nuxt project, without relying on the @nuxtjs/dotenv module. I know that this functionality has been built into Nuxt since version v2.13, so I don&ap ...

Access Denied: Could not open the file '/Users/user-name/.config/postcssrc' due to EACCES error

While attempting to run a project locally using npm run serve, I encountered an error related to postcss with no apparent solution. The situation involves transferring project files from one project to another, where the original project does not present ...

Issue with VB code behind not executing upon button click triggered by JavaScript

A scenario arises when a user is provided with a TDF text file in a report, requiring them to select two filters and fill out two fields before being able to submit. Upon clicking the "download" button without completing these requirements, a friendly erro ...

What is the best way to animate specific table data within a table row using ng-animate?

Are you working with Angular's ng-repeat to display a table with multiple rows? Do you wish to add an animation effect to specific cells when a user hovers over a row in the table? In the scenario outlined below, the goal is to have only certain cell ...

Unable to allocate an object to a variable in Angular

Currently, I am facing a challenge in my HTML page. My objective is to utilize an object by fetching it from my API and storing it in a variable for future data manipulation. The API functions properly, as it returns the Parking object with all the necessa ...

An issue occurred during the component import process in Vue.js

Perhaps it's just a small error. As someone new to this field, I'm encountering a Syntax Error with Unexpected Token in this section: component: () => import('@/layouts/default.vue'), Any idea what might be causing this issue? ...

The auto search feature seems to be malfunctioning after clicking the button

Despite my best efforts, I am still unable to resolve this issue. I have tried numerous links and code snippets, but I am encountering some difficulty in finding a solution. THE ISSUE: I have an input field with type 'Text' for searching employ ...

Upon the initial loading of the site, the Material Icon will be displayed as the title

Encountering a problem with Angular 7 and materials icon where the name of the icon is visible during the initial load of the site. Does anyone know how to address this issue? https://i.sstatic.net/SkNVY.png ...

Utilizing headless Chrome to automatically capture AJAX requests

Chrome officially supports running the browser in headless mode, allowing for programmatic control through the Puppeteer API and/or the CRI library. I've thoroughly explored the documentation but have not discovered a method to programmatically captu ...

Tips for transferring a variable from a webpage's JavaScript to Node.js

Having an issue with transferring a Javascript variable to node js for JSON file storage. The data doesn't seem to be writing to the file, possibly due to an error in the AJAX Post request or the node JS routing. The javascript is executed on an HTML ...

Having trouble coordinating a mongoose action to retrieve an array

Within the management of an employee app, I aim to segregate the business logic database operations from the main application file. A straightforward operation involves retrieving all employees from the database by using async/await for synchronization: m ...

Utilize two functions to incorporate an array of strings into an object

Currently, I'm in the process of developing a NoteEditor using react. Within my popup, I have 2 text areas. However, I have encountered an issue when attempting to add my array of strings into an object. The variable containing the arrayOfStrings retu ...

Tips for maximizing efficiency in binding data to a table that presents information in column format

I'm struggling to figure out how to effectively utilize computed properties when presenting data in columns within a table format. You can view the complete code example at jsfiddle, here's a condensed version with an explanation. My goal is to d ...

Unusual actions exhibited by the es6 object spread functionality

Check out this interesting example that showcases the power of object spread in JavaScript: module.exports = (err, req, res, next) => { err.statusCode = err.statusCode || 500; err.status = err.status || 'error'; if (process.e ...

When using VueJS to load an SVG file based on a variable within a for loop and utilizing v-html, the result returned is "[

I'm faced with a challenge of loading SVGs saved in separate files based on the content within a loop. Upon page load, what I see is: https://i.sstatic.net/OiwyT.png Hey there, check out my code snippet below: <div v-for="(rec, index) in stats ...