我有以下用于预加载图像的脚本:

export default function PreloadImages(images) {
    function loadImage(src) {
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.onload = function() {
                resolve(img);
            };
            img.onerror = img.onabort = function() {
                reject(src);
            };
            img.src = src;
        });
    }
    return Promise.all(images.map(src => loadImage(src)));
}
然后,我在Vue组件中使用它,如下所示:
PreloadImages(this.images).then(() => (this.imagesPreloaded = true));
我希望能够从中获得进度,因此可以显示2/50 Images Loaded等。我将如何去做呢?
编辑
我最终得到的是:PreloadImages.js
export default function PreloadImages(images) {
    function loadImage(src) {
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.onload = function() {
                resolve(img);
            };
            img.onerror = img.onabort = function() {
                reject(src);
            };
            img.src = src;
        });
    }
    return images.map(src => loadImage(src));
}
在我的组件内:
handlePreload() {
    PreloadImages(this.images).forEach(p => p.then(() => {
        this.imagesPreloaded++;
    }));
},

最佳答案

这是您应该采用的方法,不要引入任何额外的循环:

var imageSrcList = [
    "https://image.flaticon.com/icons/svg/565/565860.svg",
    "https://image.flaticon.com/icons/svg/565/565861.svg",
    "https://Error.Done.One.Purpose",
    "https://image.flaticon.com/icons/svg/565/565855.svg",
];

var imageContainer = document.getElementById("loadedImages");
var loadedCount = 0;

function displayCurrentLoadStatus(){
  console.log("Current load progress: ", loadedCount, " of ", imageSrcList.length);
}

function PreloadImages(images) {
    function loadImage(src) {
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.src = src;
            img.onload = function()
            {
                ++loadedCount;
                imageContainer.appendChild(img);
                displayCurrentLoadStatus();
                resolve(img);
            };
            img.onerror = img.onabort = function() {
                reject(src);
            };
        });
    }
    // Note that I removed Promise.all, let's just return a list of promises for the images passed
    return images.map((imgSrc, i)=> loadImage(imgSrc).catch((rejectedSrcError=> rejectedSrcError)));
}

// now let's create all promises for each image in images
Promise.all(PreloadImages(imageSrcList)).then( resolvedSrcList =>
{
    // Use your resolved Src's here
    console.log("Load complete: ",loadedCount, "/",resolvedSrcList.length, " images were loaded successfully.");
});
img{
    width: 60px;
    height: 60px;
    display: inline-block;
}
<div id="loadedImages"></div>

09-19 23:35