el-upload 用法
时间: 2023-11-24 22:53:11 浏览: 80
el-upload是一个基于Element UI的上传组件,可以实现文件上传的功能。它支持多文件上传,可以限制文件类型、大小等。以下是el-upload的用法:
1. 在Vue组件中引入el-upload组件:
```javascript
<template>
<el-upload
class="upload-demo"
action="/upload"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-upload="beforeUpload"
:on-success="handleSuccess"
:on-error="handleError"
:file-list="fileList"
:auto-upload="false"
:multiple="true"
:limit="3"
:accept="'image/jpeg,image/png'"
:on-exceed="handleExceed"
:disabled="disabled"
:drag="drag"
:list-type="listType"
:show-file-list="showFileList"
:http-request="httpRequest"
:with-credentials="withCredentials"
:headers="headers"
:data="data"
:name="name">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</template>
```
2. 在Vue组件的data中定义fileList数组,用于存储上传的文件列表:
```javascript
data() {
return {
fileList: []
};
}
```
3. 在Vue组件的methods中定义上传文件的回调函数:
```javascript
methods: {
handleSuccess(response, file, fileList) {
console.log(response, file, fileList);
},
handleError(err, file, fileList) {
console.log(err, file, fileList);
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
beforeUpload(file) {
console.log(file);
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 ${this.limit} 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
}
}
```
4. 在Vue组件的methods中定义上传文件的方法:
```javascript
methods: {
upload() {
this.$refs.upload.submit();
}
}
```
5. 在Vue组件的methods中定义取消上传的方法:
```javascript
methods: {
cancel() {
this.$refs.upload.abort();
}
}
```
6. 在Vue组件的methods中定义清空上传列表的方法:
```javascript
methods: {
clear() {
this.fileList = [];
}
}
```
阅读全文