有什么方法可以将变量分配给 axios 请求并在 onUploadProgress 中访问它

Is there any way to assign a variable to axios request and access it in onUploadProgress

我在 Vue 中使用以下代码。这里我使用多个axios请求同时上传多个文件。在此代码中一切正常。 但我想要一种方法来查看上传文件的百分比。看到文件对象数组 this.upload 有进度 属性。所以我想为特定对象更新此 属性。这样我就可以向用户显示文件上传进度

         for(var file of event.target.files){
            if(!this.isValidFormat(file)) continue;

            var thumb = await this.getThumb(file);
            this.upload.push({
                name: file.name,
                index: parseInt(Math.round(file.size / (1024))),
                size: (file.size / (1024 * 1024)).toFixed(2) + ' MB',
                progress: 0,
                thumbnail: thumb,
                path: null
            });

            const formData = new FormData();
            formData.append('image', file, file.name);
            formData.append('path', 'tmp');
            formData.append('index', increment);
            axios.post('web/upload', formData, {
                onUploadProgress: progressEvent => {
                    //console.log(this.config);
                    const index = parseInt(Math.round(progressEvent.total / 1024));
                    //console.log(index)
                    var u = this.upload.find(u => u.index == index);
                    if(u !== undefined){
                        u.progress = Math.floor((progressEvent.loaded * 100) / progressEvent.total);    
                    }

                }
            }).then(res => {
                this.upload[res.index].path = res.path;
                console.log(this.upload)
            });
            increment++;
        }

您可以使用 vuex 提交值并使用 getter.

https://vuex.vuejs.org/guide/mutations.html

https://vuex.vuejs.org/guide/getters.html

而不是为 onUploadProgress 使用箭头函数 - 您可以使用 bind() 向您的函数添加一个额外的第一个参数,该参数将是对相应 file 对象的引用:

  for(var file of event.target.files){
        if(!this.isValidFormat(file)) continue;

        var thumb = await this.getThumb(file);
        const fileObject = {
            name: file.name,
            size: (file.size / (1024 * 1024)).toFixed(2) + ' MB',
            progress: 0,
            thumbnail: thumb,
            path: null
        };
        this.upload.push(fileObject);

        const formData = new FormData();
        formData.append('image', file, file.name);
        formData.append('path', 'tmp');
        formData.append('index', increment);
        axios.post('web/upload', formData, {
            onUploadProgress: this.calcProgress.bind(this, fileObject)
        }).then(res => {
            this.upload[res.index].path = res.path;
            console.log(this.upload)
        });
        increment++;
    }

function calcProgress(fileObj, progressEvent)
{
     fileObj.progress = Math.floor((progressEvent.loaded * 100) / progressEvent.total);    
}