VueJS - Input Image Display Issue Causing Browser Slowdown

I'm experiencing some issues with my VueJS component that includes a file input and displays an image afterwards. Strangely, this is causing my web browsers (both Firefox and Chromium) to freeze up and use massive amounts of CPU. I tried switching to a simpler solution that doesn't utilize VueJS, using

document.getElementById('id').src = reader.result
, but even then Firefox is still not working properly. Any thoughts or suggestions on how to resolve this issue?

export default {
  name: 'test',

  template:
    '<div>' +
    '<img src="image" v-if="image">' +
    '<input type="file" @change="fileChange" />' +
    '</div>',

  data() {
    return {
      image: ''
    }
  },

  methods: {
    async fileChange(e) {
      const file = e.target.files[0]

      if (file) {
        this.image = await this.loadImage(file)
        console.log('Image is: ' + this.image)
      }
    },

    async loadImage(file) {
      return new Promise(resolve => {
        const reader = new FileReader()

        reader.onloadend = function() {
          resolve(reader.result)
        }

        reader.readAsDataURL(file)
      })
    }
  }
}

Answer №1

It appears that the reader.onloadend function is not being called, and due to the use of async and await in the fileChange method, it never completes, causing the browser to become unresponsive.

To help identify the issue, you should also include setting the FileReader.onerror property, like so:

async loadImage(file) => {
  return new Promise((resolve, reject) => {

    const reader = new FileReader()
    reader.onerrror = reject();
    // ..
  })
}

Learn more

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

Customize the appearance of the Vue.js datepicker starting from today's date

I am currently using the vue-datepicker component to display a date input field in my form. I want to set the default date to the current day and disable the selection of past dates. Additionally, I need to change the language of the component but it seems ...

Encountered an issue during my initial AJAX call

Hello everyone, I am currently attempting to use AJAX to send a request with a button trigger and display the response HTML file in a span area. However, I am encountering some issues and need help troubleshooting. Here is my code snippet: //ajax.php < ...

Update the class information using jQuery after performing an action and serialize the button's ID for AJAX requests

I'm facing an issue with two buttons on my page: <td> <button id="1" class="green-button">Publish</button> <button id="1" class="yellow-button">Delete</button> </td> The green-button and red-button have different ...

Oops! Looks like there was an error: weight is not defined when trying to calculate BMI with the HTMLButtonElement

I'm currently working on a project to create a BMI calculator following specific instructions. I've managed to follow all the guidelines except one regarding the letsCalculateBMI function. The instruction states: letsCalculateBMI should extrac ...

Tips for initiating a function at a designated scroll point on a webpage

Currently, I am testing out a code snippet that allows images to flip through in a canvas element. I'm curious if it's possible to delay the image flipping effect until the viewer scrolls down to a specific section of the page where the canvas i ...

Freemarker substitute & and &ampersand;

I am facing an issue with Freemarker. I need to eliminate all the special characters from this sentence as well as from similar sentences in the future: BLA BLA RANDOM &, RANDOM BLA In particular, I want to remove the & character. The platform ...

What is the best way to change the number 123456789 to look like 123***789 using either typescript or

Is there a way to convert this scenario? I am working on a project where the userID needs to be displayed in a specific format. The first 3 characters/numbers and last 3 characters/numbers should be visible, while the middle part should be replaced with ...

Utilizing a setTimeout function within a nested function in JavaScript

Recently delving into the world of JavaScript, I encountered an issue with a code snippet that goes like this: function job1() { var subText1 = ""; var subText2 = ""; var text = ""; var vocabulary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijkl ...

how do I modify my JavaScript code to achieve the desired outcome

How can I program a button to disable after being pressed 10 times in less than a minute, but continue counting if not pressed for 1 minute? function buttonClicked() { if (totalCount + accCounter > 9) { document.getElementById("btn").disabled = ...

In my Express Javascript application, I recently encountered a challenge where I needed to export a const outside of another

I am currently working with a file named signupResponse.js const foundRegisterUser = function(err, foundUser){ if(!err){ console.log("No errors encountered") if(!foundUser){ if(req.body.password == req.body. ...

VueJS and express implement CSRF token handling for secure POST requests

For my web application, I am using VueJS (cli 3) with axios for the front-end and NodeJS with ExpressJS for the back-end. Currently, I am working on securing the post user edit functionality by implementing CSRF tokens. In my Vue component (edit user), th ...

Ways to share code across AngularJS frontend and Node.js backend

How can code be effectively shared between an AngularJS client and a Node.js server? After creating an AngularJS application, I now need to develop a RESTful server to provide data to the client. Some Angular services used on the client-side could also be ...

What steps can I take to prevent my JavaScript code from interfering with my pre-established CSS styles?

I'm currently designing a mini-email platform that serves as a prototype rather than a fully functional application. The HTML file contains placeholder emails that have been styled to appear presentable. I've implemented an input bar and used Jav ...

Eliminate properties from a TypeScript interface object

After receiving a JSON response and storing it in MongoDB, I noticed that unnecessary fields are also being stored in the database. Is there a way to remove these unnecessary fields? interface Test{ name:string }; const temp :Test = JSON.parse('{ ...

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...

Determine the name of the Java exception class using JavaScript

Here is the code I am using to call a Java web API: m$.ajaxq({ url: contextPath + "/updateElapsedTime", type: "POST", data: params, contentType: "application/json; charset=utf-8", dataType: 'text', async: optionalRunAsync, success: ...

Why is AJAX returning false and I'm unable to figure out the reason?

My goal is to perform a database query for a keyword instantly upon input change. Currently, I am able to successfully execute the query and store all the results. However, when attempting to display the results using GET, my ajax function returns false. W ...

Getting the Tweets of a Twitter-validated user using node.js

I'm struggling with extracting Tweets from a verified user and could use some assistance. I know it's a broad question, but here's the situation: https://github.com/ttezel/twit provides a way to access tweets from any Twitter account. Howev ...

When I click on the event target, it selects the button within the span. What is the next step I should take

I have a button element that contains a span, and I want to extract the value associated with the button when it is clicked. However, if I click on the span inside the button, I am unable to retrieve the desired value because the event target points to the ...

The form within the while loop is only functioning with the initial result

Within a while loop, I have a form that is being processed with ajax. The issue is that it only works on the first form and not on the others. Can someone take a look? <?php while($a = $stmt->fetch()){ ?> <form method="post" action=""> ...