1、html
<div class="upload_box">
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:on-error="handleOnError"
:before-upload="beforeAvatarUpload"
>
<img
v-if="ruleForm.coverImage"
:src="ruleForm.coverImage"
class="cover_image"
/>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
2、JavaScript
handleAvatarSuccess(res, file) {
console.log("handleAvatarSuccess:", res, file);
this.ruleForm.coverImage = URL.createObjectURL(file.raw);
},
handleOnError(error) {
console.log("error:", error);
},
beforeAvatarUpload(file) {
let isFileType = ["image/jpeg", "image/png", "image/jpg"].includes(file.type),
isFileSize = file.size / 1024 / 1024 < 20;
if (!isFileType) this.$message.error("上传头像图片只能是jpeg/png/jpg格式!");
if (!isFileSize) this.$message.error("上传头像图片大小不能超过20MB!");
return isFileType && isFileSize;
},
3、css
.upload_box {
display: flex;
justify-content: center;
align-items: center;
width: 145px;
height: 145px;
border: 1px dashed #d9d9d9;
border-radius: 6px;
}
.cover_image {
width: 100%;
height: 100%;
}