自定义elementui文件上传组件
<template>
<el-upload
ref="uploadFileRef"
class="uploadFileCls"
drag
action=""
:limit="limit"
:auto-upload="false"
:on-change="handleFileChange"
:on-remove="handleFileRemove"
:on-exceed="handleOverLimit"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">{{ typeTip }}文件不能超过{{ limitSize }}MB!</div>
</el-upload>
</template>
<script>
export default {
name: "CustomUploadFile",
props: {
value: {
// 上传文件列表
type: Array,
default() {
return []
}
},
limitSize: {
type: Number,
default: 20
},
limit: {
type: Number,
default: undefined
},
limitType:{
type: Array,
default: () => {
return []
}
},
typeTip: {
type: String,
default: ''
}
},
data() {
return {
fileUpload: ''
}
},
watch:{},
methods: {
init() {
if (this.$refs.uploadFileRef) {
this.$refs.uploadFileRef.clearFiles()
}
},
handleFileChange(file, fileList) {
let uploadFileRef = this.$refs.uploadFileRef
// 限制文件大小
if (uploadFileRef && file.size > this.limitSize * 1024 * 1024) {
this.$message.error(`文件上传不能超过${this.limitSize}M!`)
uploadFileRef.handleRemove(file)
}
// 类型限制
if (uploadFileRef && this.limitType && this.limitType.length) {
let fileNameArray = file.name.split('.')
let fileTypeError = this.limitType.indexOf(fileNameArray[fileNameArray.length - 1]) === -1
if (fileTypeError) {
this.$message.error(`上传文件类型错误,请检查重新上传!`)
uploadFileRef.handleRemove(file)
}
}
this.emitChange(fileList)
},
handleFileRemove(file, fileList) {
this.emitChange(fileList)
},
handleOverLimit() {
this.$message.error(`只能上传${this.limit}个附件!`)
},
emitChange(fileList) {
let files = []
fileList.forEach(item => {
files.push(item.raw)
})
this.$emit('input', files)
this.dispatch('ElFormItem', 'el.form.change', files)
}
}
}
</script>