el-upload上传时实现加载动画
时间: 2025-01-10 15:06:43 浏览: 43
在Vue.js的Element UI库中,`el-upload`组件用于文件上传,为了实现上传过程中的加载动画效果,通常会在`before-upload`钩子函数内部添加一些操作。以下是一个简单的例子:
```html
<template>
<el-upload
action="your-api-url"
:on-exceed="handleExceed" // 超量限制处理
:before-upload="beforeUpload"
class="upload-demo">
<i v-if="!uploading" class="el-icon-upload"></i>
<div v-if="uploading" class="el-loading-spinner">
<i class="el-icon-loading"></i> 正在上传...
</div>
<button @click="submit">选择文件</button>
</el-upload>
</template>
<script>
export default {
data() {
return {
uploading: false,
};
},
methods: {
beforeUpload(file) {
this.uploading = true; // 显示加载状态
const formData = new FormData();
formData.append('file', file);
return new Promise((resolve, reject) => {
setTimeout(() => { // 模拟异步请求
// your request logic here, for example:
fetch('your-server-url', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(result => {
if (result.success) {
this.uploading = false; // 上传完成,隐藏加载状态
resolve(); // 成功时解决Promise
} else {
reject(); // 失败时拒绝Promise
}
})
.catch(error => {
reject(error); // 发生错误时拒绝Promise
});
}, 1000); // 模拟1秒上传时间
});
},
handleExceed(files, fileList) {
console.log(`已达到上传上限 ${fileList.length}`);
},
submit() {
// 开始上传
},
},
};
</script>
<style scoped>
.upload-demo {
display: inline-block;
}
.el-loading-spinner {
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
```
在这个例子中,当用户点击“选择文件”按钮时,`submit`方法会被触发,开始执行`beforeUpload`。这个钩子会设置`uploading`标志为`true`,显示加载图标。然后模拟一个异步请求,成功后将`uploading`设回`false`,关闭加载动画。
阅读全文
相关推荐


















