Update: When a variable changes during onUploadProgress in Vue.js, the DOM is not re

Having a bit of an issue here. I'm working on an app where users can upload images using axios. In order to enhance the user experience, I'm trying to implement a loading bar.

Here's what it looks like:

<div class="loadingbox" :style="{width: loadbar + '%'}"></div>

My data setup is as follows:

data() {
    return {
      loadbar: 0
    };
},

Axios provides the onUploadProgress function, so my plan was to use it to update the width of the div:

onUploadProgress(e) {
          let step = 100 / e.total;
          this.loadbar = e.loaded * step;
          console.log(this.loadbar);
},

When I check my console output, it shows:

0
20.334
89.32
100

However, the width of the div doesn't seem to change at all. Strangely, if I manually set loadbar: 50, then I see 50% of the progress bar.

Any insights into why Vue.js isn't registering these changes?

Update:

I tried simulating it in the created() lifecycle hook:

created() {
    let loaded = 0;
    setInterval(() => {
      loaded += 1000;
      let total = 30000;
      let step = 100 / total;
      this.loadbar = loaded * step;
    }, 1000);
}

Surprisingly, everything works perfectly fine in this scenario.

Answer №1

The issue has been identified. this is not connected to the vue instance, it is bound to the upload progress itself. To resolve this, I created a new variable called self and linked it to my vue instance:

let self = this;
 axios({
        method: "post",
        url: "/api/upload/image/profile_image",
        data: formData,
        onUploadProgress(e) {
          let step = 100 / e.total;
          self.loadbar = e.loaded * step;
        },
        ...
})

Answer №2

It appears that the main issue lies in the fact that the div element is currently empty. Below is a demonstration I conducted for testing purposes:

new Vue({
  el: "#app",
  data() {
    return {
      loadbar: 0
    };
  },
  mounted(){
    let that = this;
    const interval = setInterval(function() {
      that.loadbar += 20;
      console.log(that.loadbar)
      if(that.loadbar === 100)
           clearInterval(interval);
    }, 5000);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <div 
      class="loadingbox" 
      style="background-color:red;"
      :style="{width: loadbar + '%'}"
    >loading...</div>
</div>

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

The error occurring in the React app is a result of the page rendering prior to the API data being fetched

Utilizing the following component for my Nav, I aim to showcase the current weather based on the user's location. However, an issue arises as the page is being rendered before retrieving data from the openWeather API. import React, { useState, useEffe ...

Looking for reliable resources on establishing a connection between a Google account and my application

I am currently working on creating a react native app that aims to simplify the user login process by allowing them to link their Google account with just one click. This way, users won't have to constantly log in every time they use the app. While I ...

What is the method for retrieving this data using Javascript?

I received this JSON-encoded data: { "error": { "msg":"Concurrent verifications to the same number are not allowed", "code":10 } } and I tried to access the 'msg' value using JavaScript as follows: $("#buttonPhoneSubmit ...

Is there a way to use Puppeteer to take screenshots of a list of URLs?

Within an async function, I have set up a loop to iterate over a list of URLs. The data is sourced from an .xls file that has been converted to .json. My objective is to take a screenshot of each URL in the array, but I keep encountering an UnhandledPromis ...

Unable to turn off X-Powered-By: Express

After attempting to use app.disable("x-powered-by"); without success, I came across some helpful posts on the topic: how to remove X-Powered-By in ExpressJS Can't get rid of header X-Powered-By:Express I am using "express": "^4.16.4" as backend a ...

Revamping the vertices and UVs of DecalGeometry

I am currently experimenting with ThreeJS decals. I have successfully added a stunning decal to my sphere. Below is the code snippet I am using to place the decal on my sphere. (Please disregard any custom classes mentioned in the code.) // Creating the ...

The radio button in the HTML form is disabled when the user selects

I have two radio buttons labeled Billable "Y" and Billable "N". These radio buttons are linked to a database with corresponding values of "Y" or "N". If the user selects "Y" using the radio button, then the NonBillableReason text box should be disabled. ...

Employ the v-model directive in conjunction with a checkbox in scenarios where v-for is implemented with the properties of an object

When utilizing v-model with a checkbox in conjunction with an array of objects, it functions correctly: new Vue({ el: '#example', data: { names: [ { name: 'jack', checked: true }, { name: 'john', checked ...

Vuetify's personalized date selection tool

Utilizing Vuetify's v-date-picker in multiple components can result in code repetition. To address this, I decided to create a custom <custom-date-picker /> component that can be used wherever needed. This child component should em ...

This error message appears in vue.js: "TypeError: Trying to read an undefined property 'then'."

I am currently working on implementing email verification in my vue.js/express application. I have successfully created the user and sent emails. However, displaying a message like "verification mail sent" is not functioning as expected. The issue arises ...

Conceal a section of a container with the click of a button within a WordPress Plugin

I am currently utilizing a Wordpress plugin known as contact form 7 to construct an email list for an upcoming website project. The client has specifically requested that we avoid using services like mailchimp due to their preference of not sending ANY ema ...

Having issues with ReactJS - function not functioning properly when invoked within componentDidMount() and componentDidUpdate() lifecycle methods

I have encountered an issue that has left me puzzled, and I'm hoping someone can provide some guidance on how to solve it. The task at hand involves implementing a function that adds .active classes to li elements within a navigation bar if they cont ...

The time zones between Node 8 and Node 11 are not the same

Executing a basic new Date().toString() command produces different results on Node 11 compared to Node 8. In Node 11, the output includes the full timezone abbreviation like this: 'Fri May 10 2019 10:44:44 GMT-0700 (Pacific Daylight Time)' On t ...

"Encountering a mysterious internal server error 500 in Express JS without any apparent issues in

My express.js routes keep giving me an internal server error 500, and I have tried to console log the variables but nothing is showing up. Here are the express routes: submitStar() { this.app.post("/submitstar", async (req, res) => { ...

What is the process of including a pre-existing product as nested attributes in Rails invoices?

I've been researching nested attributes in Rails, and I came across a gem called cocoon that seems to meet my needs for distributing forms with nested attributes. It provides all the necessary implementation so far. However, I want to explore adding e ...

Learn the process of seamlessly playing multiple video files in an HTML format

I am working with multiple video files and I need them to play continuously. The goal is to seamlessly transition from one video to the next without any interruptions on the screen. Below is my current code snippet: -HTML <button onclick="playVi ...

How to use JavaScript and regex to control the state of a disabled submit button

I have a challenge where I need to activate or deactivate a submission button in a form called btn-vote using JavaScript. The button will only be activated if one of the 10 radio buttons is selected. Additionally, if the person-10 radio button is chosen, t ...

How can I reset a CSS position sticky element using JavaScript?

I have created a page where each section fills the entire screen and is styled using CSS position: sticky; to create a cool layered effect. Check it out here: https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark ...

When working with jQuery, I encountered the error message "is not a function" because I mistakenly tried to use a function more than

While working on a pager, I encountered an issue with a function that is initially invoked when the document loads. However, when attempting to use it a second time, an error "is not a function" occurs. I am curious about the reason behind this phenomenon. ...

Can a React component be configured to show only a specific array key when returning an array?

Just diving into the world of react and experimenting with different approaches to understand how I can transition into this new architecture. Currently, I have a basic component where I am returning an array of elements (mainly for testing purposes): cl ...