子规**
解决elementui里边upload上传图片组件在form表单中校验不消失问题:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210319113346202.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl81MzU4NzM3NQ==,size_16,color_FFFFFF,t_70)
项目中:
html部分
html代码
<el-form-item label="营业执照" prop="headImg">
<el-upload
:action="uploadURL"
list-type="picture-card"
:class="{hide:hideUpload}"
name="files"
:before-upload="beforeAvatarUpload"
:on-preview="handlePreview"
:on-remove="remove"
:on-change="uploadChange"
:http-request="headUpload">
<i class="el-icon-plus"></i>
<div slot="tip" class="el-upload__tip">只能上传jpg或png文件,且不超过500kb</div>
</el-upload>
<el-dialog :visible.sync="previewVisible" :append-to-body='true'>
<img width="100%" :src="previewPath" alt="">
</el-dialog>
</el-form-item>
js代码
js代码
// 营业执照上传
headUpload(params) {
let param = new FormData();
param.append("files", params.file);
axios({
url: this.adminConfig.uploadPath+"upload/upload/",
method: "post",
data: param,
headers: {
"Content-Type": "multipart/form-data"
}
}).then(res => {
this.headImg = [];
this.headImg.push(res.data.data)
})
},
// 处理图片预览效果
handlePreview(file) {
this.previewPath = file.url;
this.previewVisible = true
},
remove(file, fileList) {
if(fileList.length==0){
this.rules.headImg = [{ required: true, message: '请营业执照', trigger: 'change'}];
}
this.hideUpload = fileList.length >= this.limitCount;
},
uploadChange(file, fileList) {
this.headFile = file;
this.headFileList = fileList;
if(fileList.length==1) {
let {headImg, ...data} = this.rules;
this.rules = data;
}
this.$refs.form.clearValidate('headImg');
this.hideUpload = fileList.length >= this.limitCount;
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG && !isPNG) {
this.$message.error('上传营业执照图片只能是 JPG或png 格式!');
}
if (!isLt2M) {
this.$message.error('上传营业执照图片大小不能超过 2MB!');
}
return (isJPG || isPNG) && isLt2M;
}
css代码
.writeBox {
display: flex;
justify-content: space-between;
flex-direction: row;
flex-wrap: wrap;
width: 100%;
margin-bottom: 20px;
}
.el-row {
width: 30%;
margin-right: 10px;
margin-bottom: 8px;
}
.el-col {
white-space: nowrap;
}
.hide .el-upload--picture-card {
width: 300px;
height: 200px;
line-height: 200px;
display: none;
}
.el-form-item {
.el-input {
width:400px;
margin-right: 10px;
}
}
.el-form-item__content{
width: 800px;
}
.el-upload-list__item{
width: 300px;
height: 200px;
}