el-form手动上传文件
时间: 2023-06-13 17:02:41 浏览: 59
在使用 Element UI 的 el-form 组件时,可以通过手动上传文件来实现文件上传功能。实现步骤如下:
1. 在 el-form 中添加一个 el-upload 组件,其中 action 属性指定文件上传的 API 接口,name 属性指定上传文件的参数名。
```html
<el-form>
<el-form-item label="文件上传">
<el-upload
action="/upload"
name="file"
:show-file-list="false"
:on-success="handleSuccess"
:on-error="handleError"
>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
</el-upload>
</el-form-item>
</el-form>
```
2. 在 el-form 的 methods 中定义 handleSuccess 和 handleError 方法,用于处理上传成功和失败的回调函数。
```js
methods: {
handleSuccess(response, file, fileList) {
console.log(response)
// 处理上传成功的逻辑
},
handleError(error, file, fileList) {
console.log(error)
// 处理上传失败的逻辑
}
}
```
3. 在 handleSuccess 方法中处理上传成功的逻辑,例如显示上传成功的提示信息、更新表单数据等。
```js
handleSuccess(response, file, fileList) {
this.$message.success('上传成功')
this.form.fileUrl = response.url
}
```
4. 在 handleError 方法中处理上传失败的逻辑,例如显示上传失败的提示信息、清空表单数据等。
```js
handleError(error, file, fileList) {
this.$message.error('上传失败')
this.form.fileUrl = ''
}
```
其中,this.form 表示 el-form 组件绑定的表单数据对象。可以根据需要修改表单数据对象的属性来实现文件上传功能。