在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/C  網(wǎng)絡(luò)安全  HTML/ 使用fileReader時,已經(jīng)獲取到圖片地址,但是不顯示是什么原因?

使用fileReader時,已經(jīng)獲取到圖片地址,但是不顯示是什么原因?

本人在做項目時,使用fileReader制作圖片上傳,在成功獲取圖片的地址后,把它賦值給img的src屬性,但是圖片卻不顯示。

<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>

這里是html代碼

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,
      });
    }
  }

這里是js代碼

clipboard.png
在上傳了第二張圖片后才顯示第一張的圖片

clipboard.png

想問下為什么不行,雖然后面通過setTimeout解決了這個問題,但是不同原理,同樣想問下原因和其它的解決辦法。

我的解決辦法如下:

if (this.imgLists.length <= 5) {
  //有時候,push僅僅被添加到任務(wù)隊列中,卻沒有立即執(zhí)行,此時可以用setTimeout來是它立即執(zhí)行。
  setTimeout(()=>{
    this.imgLists.push(newImg);
  },0);
  /*this.imgLists.push(newImg);*/
}

補充一下,后來發(fā)現(xiàn)這樣方法好像還是無法解決,=。=

回答
編輯回答
枕邊人

原因:
reader.onload = function() {} 并不是阻塞的,在讀取完成之前就繼續(xù)往下走了,到this.imgLists.push(newImg);這一行的時候newImg還是空的。你setTimeout其實是在賭讀取完成需要多久,如果秒讀就能工作,否則不能,所以你實驗幾次結(jié)果不同。

解決:
把下面一串都放到異步成功的回調(diào)里面去

addImg(e) {
  let newImg = {};
  let file = e.target;
  let reader = new FileReader();
  reader.readAsDataURL(file.files[0]);
  reader.onload = () => {
    newImg.data = reader.result;
    if (this.imgLists.length <= 5) {
      this.imgLists.push(newImg);
    }
    else {
      this.$message({
        message: '最多僅支持上傳5張圖片',
        type: 'warning',
        center: true,
      });
    }
  }
}

示例:
https://jsfiddle.net/liqi0816...

2018年2月14日 14:38