<template>
<div>
<el-upload
action="#"
:style="fileList.length===0?‘margin:10px;‘:‘margin-top: 10px;‘"
list-type="picture-card"
:on-change="uploadChange"
:limit="1"
:on-exceed="handleExceed"
:file-list="fileList"
:auto-upload="false">
<i slot="default" class="el-icon-plus"></i>
<div slot="file" slot-scope="{file}">
<img
class="el-upload-list__item-thumbnail"
:src="file.url" >
<span class="el-upload-list__item-actions">
<span
class="el-upload-list__item-preview"
@click="handlePictureCardPreview(file)">
<i class="el-icon-zoom-in"></i>
</span>
<span
v-if="!disabled"
class="el-upload-list__item-delete"
@click="handleRemove(file)">
<i class="el-icon-delete"></i>
</span>
</span>
</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible" :append-to-body="true">
<img width="100%" :src="dialogImageUrl" >
</el-dialog>
</div>
</template>
<script>
import {addGoodsInfo} from "@/api/request";
export default {
name: "upload-template",
data() {
return {
fileList: [],
imageFileData: ‘‘,
dialogImageUrl: ‘‘,
dialogVisible: false,
disabled: false
}
},
mounted() {
if (this.fileList.length > 0) {
document.getElementsByClassName("el-upload el-upload--picture-card")[0].style.display = "none";
}
},
methods: {
uploadChange(file) {
this.imageFileData = file.raw;
this.fileList.push({name: file.name, url: file.url});
if (this.fileList.length > 0) {
document.getElementsByClassName("el-upload el-upload--picture-card")[0].style.display = "none";
}
},
handleExceed() {
this.$message.warning("只能上传一个图片");
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
handleRemove(file) {
this.fileList.forEach((v, index) => {
if (file.name === v.name && file.url === v.url) {
this.fileList.splice(index, 1);
}
});
if (this.fileList.length === 0) {
document.getElementsByClassName("el-upload el-upload--picture-card")[0].style.display = "";
}
},
save() {
let param = new FormData(); // 创建form对象
param.append(‘file‘, this.imageFileData); // 通过append向form对象添加数据
param.append(‘goodsInfo‘, JSON.stringify(this.goodsInfo)); // 添加form表单中其他数据
addGoodsInfo(param).then(res => {
if (res === ‘success‘) {
this.clearForm();
this.closeForm();
}
})
}
}
}
</script>
<style scoped>
</style>
vue+element 上传图片控件