element-ui文件上传添加进度条
时间: 2023-06-29 12:19:26 浏览: 98
VUE element-ui响应式步骤进度条样式代码
在使用Element-UI进行文件上传时,可以通过监听upload-progress事件来获取上传进度,然后自己实现进度条。
具体实现步骤如下:
1. 在el-upload组件上添加@upload-progress事件监听器,该事件会传递一个ProgressEvent对象,其中包含loaded和total属性,分别表示已上传的字节数和文件总字节数。
```
<el-upload
class="upload-demo"
action="/upload"
:on-progress="handleUploadProgress"
:show-file-list="false"
>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button size="small" type="success">上传文件</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
```
2. 在methods中实现handleUploadProgress方法,该方法会根据ProgressEvent对象的loaded和total属性计算出上传进度,然后更新进度条的值。
```
methods: {
handleUploadProgress(event, file, fileList) {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100)
this.uploadPercent = percent
}
}
}
```
3. 在el-progress组件上绑定value属性,该属性的值为上传进度的百分比。
```
<el-progress v-if="uploadPercent !== null" :percentage="uploadPercent" />
```
完整的代码示例:
```
<template>
<div>
<el-upload
class="upload-demo"
action="/upload"
:on-progress="handleUploadProgress"
:show-file-list="false"
>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button size="small" type="success">上传文件</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<el-progress v-if="uploadPercent !== null" :percentage="uploadPercent" />
</div>
</template>
<script>
export default {
data() {
return {
uploadPercent: null
}
},
methods: {
handleUploadProgress(event, file, fileList) {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100)
this.uploadPercent = percent
}
}
}
}
</script>
```
阅读全文