一、概述
el-uploadclearfiles是一个基于Vue.js的文件上传组件,它在原本的el-upload组件的基础上增加了清空文件的功能,可以方便地管理上传的文件。
二、使用方法
在Vue组件中引入el-uploadclearfiles:
import ElUploadClearFiles from 'el-uploadclearfiles';
export default {
components: {
ElUploadClearFiles
},
// ...
}
然后在模板中使用:
<template>
<el-uploadclearfiles class="upload-demo" ref="upload" :action="action" :on-success="handleSuccess" :on-remove="handleRemove" :on-exceed="handleExceed" :before-upload="beforeUpload" :file-size-limit="10" multiple :auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button size="small" type="success" @click="submitUpload">上传到服务器</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过10MB</div>
</el-uploadclearfiles>
</template>
以上代码中,class="upload-demo"
是为了自定义样式名,:action
是上传地址,:on-success
、:on-remove
、:on-exceed
、:before-upload
分别是上传成功、删除文件、文件超出限制、上传前的回调函数,:file-size-limit
是文件大小限制,multiple
是多选文件,:auto-upload="false"
是禁止自动上传。
三、功能介绍
1. 删除文件
el-uploadclearfiles的主要功能是允许用户添加、上传、删除和清空已上传的文件。它通过slot="action"
来指定删除按钮的位置:
<el-uploadclearfiles>
<el-button slot="trigger" type="primary">选取文件</el-button>
<el-button slot="action">删除文件</el-button>
</el-uploadclearfiles>
当点击删除按钮时,会触发on-remove
回调函数,在回调函数中可以处理删除文件的逻辑:
methods: {
handleRemove(file, fileList) {
console.log(file, fileList);
}
}
2. 清空文件
除了删除单个文件,还可以一次性删除所有已上传的文件。el-uploadclearfiles提供了一个特殊的slot="clear"
来指定清空按钮的位置:
<el-uploadclearfiles>
<el-button slot="trigger" type="primary">选取文件</el-button>
<el-button slot="clear">清空文件</el-button>
</el-uploadclearfiles>
当点击清空按钮时,会触发clearFiles
方法,它会清空文件列表,同时也会删除已上传的文件:
methods: {
clearFiles() {
this.$refs.upload.clearFiles();
}
}
3. 文件超出限制
el-uploadclearfiles可以通过on-exceed
回调函数来处理文件数量和大小的限制,如果上传的文件数量或大小超过了限制,on-exceed
函数会在上传前被调用,可以在此做出相应的提示:
methods: {
handleExceed(files, fileList) {
this.$message.warning(`当前限制为 ${this.fileSizeLimit}MB,本次只上传前${this.limitCount}个文件,请重新上传`);
}
}
4. 上传前的验证
在上传文件之前,可以通过before-upload
回调函数来检验文件的大小和类型等信息,如果不符合要求则可以阻止上传:
methods: {
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const validSize = file.size / 1024 / 1024 < this.fileSizeLimit;
if (!isJPG && !isPNG) {
this.$message.error('只能上传jpg/png文件');
}
if (!validSize) {
this.$message.error(`上传文件大小不能超过 ${this.fileSizeLimit}MB`);
}
return isJPG || isPNG && validSize;
}
}
四、总结
el-uploadclearfiles是一个功能强大且易于使用的文件上传组件,它提供了丰富的接口和回调函数,可以方便地管理上传的文件。通过本文的介绍,相信大家已经对el-uploadclearfiles有了更深入的理解,可以灵活地使用它完成文件上传的需求。