What is the best way to ensure that the DOM reflects the computed data in a VUE.js Project?

I was learning how to upload images to Firebase Storage by following a video tutorial. The tutorial can be accessed at this link: https://www.youtube.com/watch?v=SpxHVrpfGgU&feature=youtu.be.

Instead of replicating the example app in the tutorial, I tried to build it using Vue.JS and Vuetify. Everything seemed to work fine except for one issue - the progress bar did not update with the upload percentage. Even though I could see the uploadPercentage changing in the console log, it just wouldn't render on the screen. Does anyone have any insights into why this might be happening and how I can fix it?

Here is the code snippet:

<template>
  <v-container style="height: 100%;">
      <v-row
        style="height: 30%;"
      ></v-row>
      ...
    </v-container>
</template>
<script>
import firebase from '@/firebase/init'

export default {
  data: () => ({
    file: null,
    imageURL: null,
    uploadPercentage: 0
  }),
  methods: {
    onFileChange () {
      let reader = new FileReader()
      reader.onload = () => {
        reader.imagUrl = reader.result
      }
      reader.readAsDataURL(this.file)
    },
    onUpload () {
      // create a firebase storage ref
      var storageRef = firebase.storage().ref('public_wall/' + this.file.name)

      // upload file
      var task = storageRef.put(this.file)

      // update progress bar
      task.on('state_changed',

        function progress (snapshot) {
          var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
          console.log(percentage)
          this.uploadPercentage = percentage
          console.log(this.uploadPercentage)
        },

        function error (err) {
          console.log(err)
        },

        function completed () {

        }

      )
    }
  }
}
</script>

Answer №1

Two issues caught my eye.

First and foremost:

:value="Per"

should actually read:

:value="uploadPercentage"

Another concern is that your this may not be referencing the correct object within the progress function. Switching to an arrow function can help maintain the value of this to align with the surrounding scope:

task.on('state_changed',
  snapshot => {
    var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
    console.log(percentage)
    this.uploadPercentage = percentage
    console.log(this.uploadPercentage)
  },
  // etc.

You can verify this issue by using console.log(this) within your function.

There are several ways to address this, such as moving the function into its own Vue method. Functions in the methods section of Vue automatically bind to the appropriate this.

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

Using JavaScript to toggle the visibility of an HTML div element

I'm looking to enhance the functionality of this show/hide HTML div using JavaScript. HTML <a href="#" class="clickme">Menu 1</a> <div class="box"> <span><span class="labelText"><span></span>Number 1</ ...

Convert traditional class-based styles to inline styles

Is there a tool available that can efficiently convert class-based styles to inline styles? I am designing an email and find it much easier and quicker to work with classes, but the final output requires inline styles. It seems like there should be softwar ...

Utilizing Vue and Django: The best method for distinguishing publicPath from static file prefix

The process of transforming my extensive Django project, which currently integrates Vue from a CDN on individual frontend pages, into a Single Page Application (SPA) using NPM has presented some challenges. The backend and frontend are now separate entitie ...

Do not need to refresh the form

I developed a PHP-based Feedback form that includes a Popup from Foundation 5. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> .auto-style1 { margin-left: 1px; ...

The external function in HTML Form's onsubmit attribute is failing to execute

My HTML Form has an onsubmit event that should call a validate() function. Everything works fine when the validate() function is inside a script tag at the end of the body tag. But if the validate() function is in an external JavaScript file, like in thi ...

JavaScript tip: How to disregard symbols that affect the length of text in a textbox?

I am working on a task which involves counting only the text, excluding symbols, entered in a textbox. For instance, if a user types email_ex_3/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05374568646c692b666a68">[email ...

How can angular DI be effectively implemented with libraries such as Modernizr, lodash, and jquery plugins to optimize performance and functionality?

As I delve into the world of Angular, I've noticed that it's not very common to wrap third-party scripts in an AngularJS provider for dependency injection. I'm still trying to figure out the best approach to leverage DI with jQuery plugins, ...

The functionality of my script relies on the presence of an alert function within it

My code seems to only work when I include an alert function in it. I'm trying to make my div scroll to the bottom. I've done some research, but for some reason, the script doesn't run without an alert function. $(document).ready(function ...

Node.js encountering difficulties with updating files

Struggling with updating my users' points continuously every x amount of seconds. Despite looping through each user, only the last user receives the 10 additional points when it goes through the loop... Any suggestions would be greatly appreciated! s ...

Creating a reusable service for making REST API calls with $http

I am in need of a versatile service that I can call from my controller with the ability to pass options dynamically. For Instance. var app = angular.module('common', []); app.factory('APIService', ['$http', function($http){ ...

Improprove lazy loading in Vue.js by utilizing webpack chunks. Explore the differences between using import and require-resolve

When it comes to lazy loading with webpack chunks, I've discovered two methods - one involves using require & resolve, and the other involves using import. The require & resolve method: const Home = resolve => { require.ensure(['co ...

Preventing touchstart default behavior in JavaScript on iOS without disrupting scrolling functionality

Currently experimenting with JavaScript and jQuery within a UIWebView on iOS. I've implemented some javascript event handlers to detect a touch-and-hold action in order to display a message when an image is tapped for a certain duration: $(document) ...

Why am I seeing a blank page?

I've recently started learning React and I'm facing an issue where the header and paragraph are not showing up on my page. Here's a snippet from my script tag with the type set to text/babel: var myElements = React.createClass({ render: ...

Avoiding React App from refreshing when form is submitted

Every time I hit the enter key while typing in the form, the application refreshes. My goal is to capture the input from the form as a value and set the state with that value. <form> <input value={input} disabled= ...

NextJS allows for custom styling of Tiktok embeds to create a unique and

Currently, I am in the process of constructing a website that integrates Tiktok oEmbed functionality. Thus far, everything is running smoothly, but I have encountered an issue - how can I customize the styling to make the body background transparent? I ha ...

Exploring byte array manipulation in node.js and techniques for data processing

Currently, I am faced with the challenge of retrieving a full byte array from a socket and then inserting it into a BLOB database without formatting the data. This is necessary as I specifically need to maintain the structure of the byte array. Initially, ...

Changing the key of a nested item within an array of objects using JavaScript

My task in JavaScript is to change the names of canBook -> quantity, variationsEN -> variations, and nested keys valueEN -> value. var prod = [{ price: 10, canBook: 1 }, { price: 11, canBook: 2, variationsEN: [{ valueE ...

Issue related to conflicting jQuery references and receiving multiple versions of jQuery simultaneously

Despite having only a reference to jQuery version 1.9.1 in the scripts, version 1.8.2 is somehow being added to the solution. The script used to add it is: bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js")); Althou ...

Change the color of a table cell on two consecutive clicks using jQuery

Hey there! I've got this super simple code that does the job of changing the background color of a selected cell in a table to red. It's pretty awesome and works like a charm. Here's the CSS: .fixture-table td.team.on { background-colo ...

Creating a program to ascertain whether two integers inputted by a user are odd numbers

I need assistance in creating a function that can ascertain whether two numbers input by the user are odd and then return a boolean value that is true only if both numbers are odd. I'm already familiar with creating a function to check for even number ...