1.引入element图片上传组件
<el-upload
:class="{ hide: hideUpload }" //单图上传关键
accept=".png, .jpg, .jpeg" //格式控制
action="https://api-test.XXXXX.cn/material/upload/image" //上传地址
list-type="picture-card" //类型
:on-preview="handlePictureCardPreview" //单击图片事件
:on-remove="handleRemove" //删除事件
:on-change="onchange" //图片改变事件
:on-success="onsuccess" //成功事件 主要是这里取值
:headers="headers" //请求头
>
<i class="el-icon-plus"></i>
</el-upload>
2.在data中定义变量
imageUrl: "", //图片绑定值
hideUpload: false, //单图控制变量
limitCount: 1, //同上 关键!
headers: {},
3.方法
onchange(file, fileList) {
console.log("图片地址" + file.response);
console.log(fileList);
this.hideUpload = fileList.length >= this.limitCount; //控制单图
},
//上传成功
onsuccess(response, file, fileList) {
console.log(file);
console.log(response); //response里就是上传成功后返回的值 包括图片地址 id等
console.log(response.data.materialId);
this.imgUrl = response.data.materialId;
console.log(fileList);
},
//删除图片
handleRemove(file, fileList) {
console.log(file, fileList);
this.hideUpload = fileList.length >= this.limitCount; //控制单图
},
//点击图片方法
handlePictureCardPreview(file) {
console.log(file);
// console.log("图片地址:" + this.dialogImageUrl);
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
4.style
.hide .el-upload--picture-card {
display: none;
} //单图 去掉scoped 目的是为了修改element-ui自带的样式
//elementui样式
.avatar-uploader-icon {
border: 1px dashed #d9d9d9 !important;
}
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9 !important;
border-radius: 6px !important;
position: relative !important;
overflow: hidden !important;
}
.avatar-uploader .el-upload:hover {
border: 1px dashed #d9d9d9 !important;
border-color: #409eff;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 300px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 200px;
height: 178px;
display: block;
}