|
项目有文件上传功能,文件上传过程中,通过Loading遮罩:
const loading = Loading.service({
lock: true,
text: '文件上传中',
spinner: 'el-icon-loading'
});

展示上传过程,小文件上传体验尚可,但在上传大文件时,界面被长期占用体验较差。
希望能动态修改展示文本text,将上传进度显示在其上。
解决方法
项目由Vue构建,用axios实现上传,axios的config属性由data传入,
Loading.service被实例化为loading:
config: {
headers: {
'token': Cookies.get('token'),
'Content-Type': 'multipart/form-data'
},
}
const loading = Loading.service({
lock: true,
text: '文件上传中',
spinner: 'el-icon-loading'
});
axios.post(upurl, param, config)
.then(response => {
loading.close();
if (response.data.code !== 0) {
alert(response.data.message);
}
else {
alert('上传成功!请刷新页面');
}
})
于是我定义了request函数,通过在return中加入回调函数progressEvent实现监听上传进度,
给回调函数传入loading实例,在回调函数中计算上传百分比uploadPercentage并通过loading.setText("")方法修改loading实例的text属性。
axios.post(upurl, param, request(loading))
.then(response => {
loading.close();
if (response.data.code !== 0) {
alert(response.data.message);
}
else {
alert('上传成功!请刷新页面');
}
})
request(loading) {
return {
headers: {
'token': Cookies.get('token'),
'Content-Type': 'multipart/form-data'
},
onUploadProgress: progressEvent=>{
if(progressEvent.lengthComputable){
let uploadPercentage = (progressEvent.loaded / progressEvent.total) * 100;
loading.setText('已上传:['+uploadPercentage+'%]');
}
else console.log('error');
},
}
}
最终效果:

遇到的问题
最初,尝试在data中直接修改config,在config中加入回调函数,
并在data中定义新的percentage变量,注册实例时将percentage传入text,
但这样的操作会导致text只能够保存初值,后续不会实现进度的动态加载。
config: {
headers: {
'token': Cookies.get('token'),
'Content-Type': 'multipart/form-data'
},
progressEvent => {
if(progressEvent.lengthComputable){
this.percentage = (( (progressEvent.loaded / progressEvent.total) * 100) | 0);
}
else console.log('error');
}
}
let loading = Loading.service({
lock: true,
text: '文件上传进度:['+this.percentage+'%]',
spinner: 'el-icon-loading'
});
|