<template>
<el-upload ref="upload" class="upload-demo" :action="uploadUrl"
:on-success="handleSuccess" :file-list="fileList" :show-file-list="true" multiple list-type="picture-card"
:on-preview="handlePreview" :on-remove="handleRemove" >
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible2">
<img width="100%" :src="dialogImageUrl" alt="" />
</el-dialog>
</template>
<script>
data(){
return{
dialogVisible2:false,
// 上传的图片服务器地址(换成自己的htpp图片路径)
uploadUrl: process.env.VUE_APP_BASE_API + "/system/pic/avatar",
//上传
fileList: [],
dialogImageUrl: "",
form:{
productPicArr :null
}
}
}
methods:{
//图片成功回调
handleSuccess(response, file, fileList) {
//主要用于后端返回的图片格式和自己又添加的图片
this.fileList = fileList;
try {
//过滤出有response的
let a = fileList.filter((item) => item.hasOwnProperty("response"));
//过滤出没有response的
let b = fileList.filter((item) => !item.hasOwnProperty("response"));
//有response的进行遍历
let have = a.map((res) => {
return res.response.id;
});
//没有response的进行遍历
let Nohave = b.map((res) => {
return res.id;
});
//数组合并
this.form.productPicArr = have.concat(Nohave);
} catch (error) {}
},
// 点击预览图片
handlePreview(file) {
this.dialogImageUrl = file.url || file.thumbUrl;
this.dialogVisible2 = true;
},
// 删除图片
handleRemove(file, fileList) {
this.fileList = fileList;
try {
//过滤出有response的
let a = fileList.filter((item) => item.hasOwnProperty("response"));
//过滤出没有response的
let b = fileList.filter((item) => !item.hasOwnProperty("response"));
//有response的进行遍历
let have = a.map((res) => {
return res.response.id;
});
//没有response的进行遍历
let Nohave = b.map((res) => {
return res.id;
});
//数组合并
this.form.productPicArr = have.concat(Nohave);
} catch (error) {}
},
//点击修改按钮图片的回显
handleUpdate() {
getCustom(id).then(response => {
if(response.data.productPicArr !== null) {
this.fileList = response.data.productPicArr.map((item) => {
return { ...item, url: process.env.VUE_APP_BASE_API + item.url };
});
}
this.form = response.data;
});
},
//修改后提交的按钮
submitForm(){
//判断是否为对象进行处理
if (this.form.productPicArr !== null) {
this.form.productPicArr = this.form.productPicArr.map((res) => {
if (res !== null && typeof res === "object") {
return res.id;
} else {
return res;
}
});
//然后调用修改接口
updateCustom(this.form).then(response => {
this.$modal.msgSuccess("修改成功");
this.fileList = []
});
}
}
</script>
当需要给后端传一个数组里面是每张图片的id时,列如 productPicArr :[412,413,414],
点击修改图片回显后端返回的是一个数组对象,对象里有图片的地址和图片的id,满足以上即可复制使用