When using fileReader, you have already obtained the image address, but what is the reason for not displaying it?

when I am working on the project, I use fileReader to upload the picture. After successfully getting the address of the picture, I assign it to the src attribute of img, but the picture is not displayed.

<div class="upload-box">
    <ul>
      <li  v-for="(item,index) in imgLists">
        <img v-if="item.data != """ :src="item.data" :alt="index">
        <span></span>
      </li>
    </ul>
    <input type="file" @change="addImg($event)" accept="image/png">
  </div>

here is the html code

addImg(e) {
    let newImg = {};
    let flag = this.flag;
    let file = e.target;
    let reader = new FileReader();
    reader.readAsDataURL(file.files[0]);
    reader.onload = function() {
      newImg.data = this.result;
      flag = true;
      setTimeout( ()=>{
        flag=false;
      },1000);
    }
    if (this.imgLists.length <= 5) {
      this.imgLists.push(newImg);
    }else{
      this.$message({
        message: "5",
        type: "warning",
        center:true,
      });
    }
  }

here is the js code

clipboard.png

clipboard.png

I would like to ask why not. Although I solved this problem later through setTimeout, I would also like to ask the reasons and other solutions for different principles.

my solution is as follows:

if (this.imgLists.length <= 5) {
  //pushsetTimeout
  setTimeout(()=>{
    this.imgLists.push(newImg);
  },0);
  /*this.imgLists.push(newImg);*/
}

add, later found that this method still can not be solved, =. =

Mar.20,2021

reason:
reader.onload = function () {} is not blocked, it continues to go down before the read is complete, and newImg is still empty when it reaches the line this.imgLists.push (newImg); . You setTimeout are actually betting on how long it will take to complete the read, if it works in seconds, otherwise you can't, so the results of several experiments are different.

solve:
put the following string into the asynchronous successful callback

  https://jsfiddle.net/liqi0816.

Menu