<el-form-item label="照片" prop="staffImg">
<template v-slot:label>
<span v-show="!rules.staffImg[0].required"
style="color: #ff4949;margin-right: 4px;">*</span>
<span>照片</span>
</template>
<el-upload class="avatar-uploader" :action="action" ref="upload" :show-file-list="false"
:on-change="uploadChange" :headers="headers" :before-upload="fileBeforeUpload"
:on-success="fileUploadSuccess" accept=".jpg,.png">
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
// 表单校验
rules: {
staffImg: [
{ required: true, message: "图片不能为空", trigger: ["blur", 'change'] },
],
},
computed: {
// 上传头像
action() {
let baseUrl = "";
if (process.env.NODE_ENV === "development") {
baseUrl = process.env.VUE_APP_BASE_API + "/base/common/uploadFile";
} else {
baseUrl = process.env.VUE_APP_BASE_API + "/base/common/uploadFile";
}
return baseUrl;
},
},
uploadChange(file, fileList) {
// console.log("上传进行改变", this.imageUrl);
this.headFile = file;
this.rules.staffImg[0].required = false;
},
//图片上传之前
fileBeforeUpload(file) {
const that = this;
let size = file.size / 1024 / 1024;
if (size >= 1) {
that.$modal.msgError("上传图片过大!请上传1M以内的图片");
return;
}
const isJpgOrPng =
file.type === "image/jpeg" || file.type === "image/png";
// const isLt1M = file.size / 1024 / 1024 < 1;
const isLt1M = true;
if (!isJpgOrPng) {
this.$message.error("上传图片只能是 JPG 或 PNG 格式!");
return false;
}
// 加密
const time = toString(new Date().getTime());
const p = encrypt(time);
this.headers["s"] = p;
this.headers["t"] = time;
return new Promise((resolve) => {
// 小于1M 不压缩
if (isLt1M) {
resolve(file);
}
// 压缩到400KB,这里的400就是要压缩的大小,可自定义
imageConversion.compressAccurately(file, 200).then((res) => {
resolve(res);
});
// compressAccurately有多个参数时传入对象
imageConversion
.compressAccurately(file, {
size: 1024, //图片大小压缩到1024kb
width: 1280, //宽度压缩到1280
})
.then((res) => {
resolve(res);
});
});
},
//照片上传成功
fileUploadSuccess(res, file) {
this.form.staffImg = res.data.dbPath;
this.imageUrl = URL.createObjectURL(file.raw);
this.rules.staffImg[0].required = false;
},
原理就是写一个假的红色*号,每次点击查看的时候执行 this.rules.staffImg[0].required = false;
关闭原有的非空验证,打开假的红色*号
表单重置的时候执行this.rules.staffImg[0].required = true;
上传文件改变后执行this.rules.staffImg[0].required = false;
图片上传成功后执行this.rules.staffImg[0].required = false;