Element UI 文件上传组件实现教程
在 Element UI 中,可以通过 el-upload 组件来实现文件上传功能。
- 首先需要在 Vue 中引入 el-upload 组件:
<template>
<el-upload
class='upload-demo'
action='https://jsonplaceholder.typicode.com/posts/'
:on-preview='handlePreview'
:on-remove='handleRemove'
:before-upload='beforeUpload'
:on-success='handleSuccess'
:on-error='handleError'
:file-list='fileList'
:auto-upload='false'
list-type='picture'
:multiple='true'
:limit='3'
:on-exceed='handleExceed'
:disabled='uploadDisabled'>
<el-button size='small' type='primary'>点击上传</el-button>
<div slot='tip' class='el-upload__tip'>只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</template>
- 在 data 中定义 fileList 数组,用来存储上传的文件:
data() {
return {
fileList: []
}
}
- 编写上传前的校验方法 beforeUpload,限制上传文件的类型和大小:
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isJPG && isLt2M
}
- 编写上传成功的回调方法 handleSuccess,将上传成功的文件添加到 fileList 数组中:
handleSuccess(response, file, fileList) {
this.fileList = fileList
}
- 编写上传失败的回调方法 handleError,提示上传失败的原因:
handleError(error, file, fileList) {
this.$message.error('上传文件失败: ' + error.message)
}
- 编写上传文件数量超过限制的回调方法 handleExceed,提示超过限制的原因:
handleExceed(files, fileList) {
this.$message.warning(`只能上传 ${this.limit} 个文件,已经选择了 ${files.length} 个文件。`)
}
- 最后,可以在 methods 中定义 handlePreview 和 handleRemove 方法,分别用来预览和删除上传的文件。
以上就是 Element UI 实现文件上传的基本步骤。
原文地址: https://www.cveoy.top/t/topic/lAwO 著作权归作者所有。请勿转载和采集!