在vue中使用微信jssdk的getLocalImgData怎么让多张图片显示

在循环里添加了一个异步请求类型的,所以我让他每次执行完毕后再执行下一次操作,其中用到了async 和 await,将异步变为同步去执行。

 1 // 图片上传
 2     handleImage(typeVal) {
 3       const uploadObj = this.imgData.uploadType.find(
 4         (item) => item.typeVal === typeVal
 5       );
 6       const count = uploadObj ? 5 - uploadObj.addFiles.length : 5; //图片数量
 7       const that = this;
 8       wx.chooseImage({
 9         count: count,
10         sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图,默认二者都有
11         sourceType: ["album", "camera"], // 可以指定来源是相册还是相机,默认二者都有
12         success: function (res) {
13           that.$toast.loading({
14             message: "加载中...",
15             duration: 0,
16             forbidClick: true,
17           });
18           var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
19           that.localIds = res.localIds;
20           that.readImages(localIds, typeVal);
21         },
22         fail: function () {
23           that.$toast.clear(); //关闭加载
24         },
25       });
26     },
1   async readImages(localIds, typeVal) {
2        this.imgFiles = [];
3        for (var i = 0; i < localIds.length; i++) {
4          await this.doReadImage(localIds[i], typeVal,i);
5        }
6    },     
  doReadImage(localId, typeVal,i) {
       const that = this;
       return new Promise((resolve) => {
         wx.getLocalImgData({
           //获取图片Base64数据
           localId, // 图片的localID
           success: function (res) {
             var localData = res.localData; // localData是图片的base64数据,可以用img标签显示
             if (localData.indexOf("data:image") < 0) {
              //安卓处理
               localData = "data:image/jpeg;base64," + localData;
             }
             //base64转文件流
             const fileData = that.dataURLtoFile(localData);
             //不压缩图片
             //files.push({data:localData,size:fileData.size});
             //压缩图片
             that.imgFiles.push(fileData);
             const files = that.imgFiles;
             if (i+1 === that.localIds.length) {
               that.uploadIpt({ files }, typeVal);
             }
             resolve("done!");
           },
           fail: function () {
             that.$toast.clear(); //关闭加载
           },
         });
       });
     },
  //base64转文件流
     dataURLtoFile(dataurl, filename = "") {
       var arr = dataurl.split(","),
         mime = arr[0].match(/:(.*?);/)[1],
         bstr = atob(arr[1]),
         n = bstr.length,
         u8arr = new Uint8Array(n);
       while (n--) {
         u8arr[n] = bstr.charCodeAt(n);
       }
       return new File([u8arr], filename, { type: mime });
     },
那些看似不起波澜的日复一日,会突然在某一天让人看到坚持的意义。
原文地址:https://www.cnblogs.com/Dcode/p/14511357.html