"Vue and axios fail to refresh the DOM even after the value has been modified

I am currently working on a loop for uploading files.

      this.fileUpload.filter((file) => !file.error)
        .map((file, index_file) => {
          var formData = new FormData();
          formData.append("folderID", id);
          formData.append("folderName", name);
          formData.append("type", type);
          formData.append(`content`, file);

          fileService
            .uploadfiles(
              formData,
              (event) => {
                file.status = "uploading";
                file.uploadPercentage =
                  Math.round((event.loaded * 100) / event.total) * 0.9;
                if (file.uploadPercentage == 90) {
                  file.status = "uploaded";
                }
                console.log(  file.uploadPercentage);
              }
            )
            .then((result) => {
              file.uploadPercentage = 100;
              file.status = "done";
            })
            .catch(() => {
              file.status = "uploaded";
            });
        });

Just a little reminder: fileService.uploadfiles function is used to create a function that calls axios.post method.

Also, remember to include a div element to display the uploading progress:

   <div v-for="(file, file_index) in fileUpload" :key="`file_preview_${file_index}_${file.name}_${file.status}`">

{{ file.uploadPercentage }}
</div>

If you encounter an issue where the percentage on the div element does not update while the console logs correctly, make sure to troubleshoot and identify the root cause.

image here

Answer №1

To manually update the virtual dom, utilize the $forceUpdate() method

fileService
        .uploadfiles(
          formData,
          (event) => {
            file.status = "uploading";
            file.uploadPercentage =
              Math.round((event.loaded * 100) / event.total) * 0.9;
            if (file.uploadPercentage == 90) {
              file.status = "uploaded";
            }
            console.log(  file.uploadPercentage);
            this.$forceUpdate()
          }
        )
        
     

Answer №2

To trigger a refresh and include v-if re-render, I incorporated $nextTick into an arrow function within the template.

uploadfiles(
              formData,
              (event) => {
                file.status = "uploading";
                file.uploadPercentage = Math.round((event.loaded * 100) / event.total) * 0.9;
                this.rerenderProgress = false;
                this.$nextTick(function () {
                  this.rerenderProgress = true;
                });
                // this.$forceUpdate();
                if (file.uploadPercentage == 90) {
                  file.status = "uploaded";
                }
              },
              { cancelToken }
            )

Answer №3

If you encounter any reactivity limitations in Vue, remember to utilize Vue.set as described in the provided link.

There are certain changes that Vue may not directly detect due to JavaScript constraints. Nevertheless, there exist workarounds to maintain reactivity within your application.

Vue.set(item, 'status', 'processing');
Vue.set(item, 'progressPercentage', Math.round((event.loaded * 100) / event.total) * 0.9);

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

What is causing .then() to not wait for the promise to resolve?

I'm currently delving into an Angular project, and I must admit, it's all quite new to me. My confusion lies in the fact that the .then() function doesn't seem to be waiting for the promises to resolve. Could this have something to do with ...

External variable accessing the getjson function

I have a question about optimizing the usage of the title variable within the getJSON function. Here's a sample code snippet that I'm working with: for (var x = 0; x < temp_addresses.length; x++) { var title = temp_addresses[x].title; ...

Retrieve a single value from a JavaScript array

There must be something simple I am missing here, as all the search results I found relate to looping over arrays, which is not what I want. My ajax call returns a response in the form of a straightforward array. When I use console.log(response); in the s ...

Vue transition not functioning properly when hovering over text for changes

When you hover over the circular region on the website, the text and description in the red box will change. To add a fade animation effect when the text changes, I attempted to use <transition> as per the documentation provided in this link. Unfor ...

Struggling with determining the perfect transition speed for the sidemenu display

I'm a newcomer to web development and facing an issue with setting the transition speed for opening and closing this side menu. Despite adding transitions in the CSS and specifying duration in the Javascript, the menu continues to open instantly. I di ...

Modify the website address and show the dynamic content using AJAX

$(function(){ $("a[rel='tab']").click(function(e){ //capture the URL of the link clicked pageurl = $(this).attr('href'); $("#Content").fadeOut(800); setTimeout(function(){ $.ajax({url:pageurl+'?rel=tab&apo ...

Adjusting the hue of the Vuetify app-bar expansion

Is there a way to change the color of the v-app-bar extension separately from the v-app-bar itself? I have looked through the documentation but couldn't find any information on this. It seems like a simple customization that many people would be inter ...

Exploring the Concept of Constructor Interfaces in TypeScript

I need some help with understanding constructor interfaces in TypeScript. I am new to this concept and I'm struggling to grasp how they are type checked. Let's take a look at an example from the documentation: interface ClockConstructor { ne ...

Obtaining the text from an element in Selenium using JavaScript

I've been trying to figure this out, and it seems like it should be a simple task, but how can I extract the text from a table displayed in a browser? When I use the "inspect" tool, the code snippet looks something like this: <tr role="row&qu ...

Encountering a module injection error in AngularJS related to the ui.grid feature during my first experience with it

Trying to develop an AngularJS app, encountering the following error upon running the code: Uncaught Error: [$injector:modulerr] Failed to create module myApp: Error: [$injector:modulerr] Failed to create module ui.grid: Error: [$injector:nomod] Module &a ...

Failure to trigger custom event on FB pixel

I have installed the FB pixel helper browser plugin and I am confident that the FB pixel is properly implemented, as it is tracking pageviews correctly. However, I am facing an issue where the code for reporting a custom event is not working, even though ...

The powerful combination of knockout.js, breeze, and dynatree/fancytree offers a dynamic and

This concept is really challenging for me to grasp as I am not accustomed to this particular style of programming or data management. Presently, my main objective is to pass a JSON object retrieved through Breeze into a Dynatree or Fancytree. All the ava ...

The asynchronous `beforeEach` function in the router activates two different

I'm facing an issue where two routes are being triggered when I'm trying to wait for an asynchronous response in my route guard. The problem arises when the page loads, with the "/" route being hit instantly followed by the targeted route. router ...

Interface-derived properties

One of the challenges I'm facing is dealing with a time interval encapsulation interface in TypeScript: export interface TimeBased { start_time: Date; end_time: Date; duration_in_hours: number; } To implement this interface, I've created ...

Tips for ensuring math formulas display correctly in CKEditor

I'm currently struggling to properly display the correct format of a math formula in ckeditor. I have made numerous attempts to find a solution, but so far, none have been successful. Here is an excerpt of my code: <html> <head> <scr ...

The pdf2json encountered an error when attempting to process a PDF file sent via an HTTP

I am encountering an issue while attempting to extract information from PDF files using a nodejs script. Upon running the program, I encounter the following error: Error: stream must have data at error (eval at <anonymous> (/Users/.../node_modules/ ...

Tips for utilizing the /foo-:bar pathway in Nuxt.js?

I am trying to utilize the router /foo-:bar in Nuxt. Do you have any suggestions on how I could make this work? I attempted using pages/foo-_bar.vue but it did not yield the desired results. ...

Why is it necessary to use 'then' on the response JSON when using the Fetch API? It's like trying to decipher the hidden meaning

While delving into the realm of promises, I decided to test it out with a basic GET request on Twitch. Yet, one aspect is still puzzling me - why does json() return a promise? The response already contains the data, so what's the deal with it being wr ...

What is the process for pulling out a specific JSON element based on a condition?

I am working with a JSON object that looks like this: "links" : [ { "rel" : "first", "href" : "http://localhost:8080/first" }, { "rel" : "self", "href" : "http://localhost:8080/self" }, { "rel" : "next", "href" : "http://loca ...

Dynamic links within Vue router can cause issues with page reloading and some components not loading correctly

Within my project's routes file, I have added a new path with nested children: path: '/warehouse/:id', name: 'ShowWarehouse', component: ShowWarehouse, children: [{ path: 'edit', name: 'EditWarehouse ...