element-ui文件上传添加进度条
时间: 2023-09-02 12:05:45 浏览: 50
要在 Element-UI 中实现文件上传进度条,你需要使用 axios 库来发送请求并跟踪上传进度。以下是一个简单的示例:
首先,你需要在组件中引入 axios 库:
```
import axios from 'axios'
```
然后,在你的上传方法中,使用 axios 发送 POST 请求,并将上传进度作为回调函数传递给 axios:
```
uploadFile() {
const formData = new FormData()
formData.append('file', this.file)
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: progressEvent => {
this.uploadPercentage = parseInt(Math.round((progressEvent.loaded * 100) / progressEvent.total))
}
})
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})
}
```
注意,`onUploadProgress` 是 axios 的一个选项,它将上传进度作为参数传递给你的回调函数。在这个例子中,我们使用 `parseInt` 和 `Math.round` 来计算上传百分比,并将其存储在组件的 `uploadPercentage` 数据属性中。
最后,在你的模板中,你可以使用 Element-UI 的进度条组件来显示上传进度:
```
<el-progress :percentage="uploadPercentage"></el-progress>
```
这将根据上传进度动态更新进度条的进度。