<template>
<div>
<div class="show-img">
<template v-if="fileList.length">
<div class="img-box" :class="{ marginRight: index !== fileList.length - 1 }"
v-for="(url, index) of fileList">
<img :src="url" alt="" />
<div class="icon-group">
<i class="el-icon-search check" @click="handlePictureCardPreview(index)"></i>
<i class="el-icon-delete" @click="delFile(index)"></i>
</div>
</div>
</template>
<div class="upload-box" @click="fileUpload" v-show="fileList.length < limit && !uploading">
<input type="file" id="btn_file1" @change="fileChange" style="display: none" />
<i class="el-icon-plus avatar-uploader-icon"></i>
</div>
<div class="upload-box" v-show="uploading" v-loading="uploading"></div>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="" />
</el-dialog>
</div>
</div>
</template>
<script>
import Cookies from "js-cookie";
import { uploadFile } from "../../api/picture";
export default {
name: "upload-Img",
props: {
file: {
type: Array,
default: () => [],
},
limit: {
type: Number,
default: 2,
},
},
watch: {
file: {
handler: function (n) {
this.fileList = n;
},
},
},
data() {
return {
fileList: [],
imageUrl: "",
uploading: false,
headers: {
Authorization: Cookies.get("vue_admin_template_token"),
},
dialogImageUrl: "",
dialogVisible: false,
};
},
mounted() {
this.fileList = this.file
},
methods: {
handlePictureCardPreview(index) {
this.dialogImageUrl = this.fileList[index];
console.log(this.fileList);
this.dialogVisible = true;
},
fileChange(response, file, fileList) {
console.log(this.files, response, file, "gaibian");
let that = this
let formData = new FormData();
formData.append("file", response.target.files[0]);
uploadFile(formData)
.then((res) => {
console.log(res);
that.uploading = false;
that.fileList.splice(0, 1)//只能有一张答案图片
that.fileList.push(res.data[0]);
that.$emit("fileChange", that.fileList);
})
.catch((err) => {
console.log(err);
that.uploading = false;
});
},
///附件删除
delFile(index) {
this.fileList.splice(index, 1);
},
fileUpload() {
document.getElementById("btn_file1").click();
},
},
};
</script>
<style scoped lang="scss">
.marginRight {
margin-right: 10px;
}
.show-img {
&>div {
float: left;
}
&::after {
content: "";
display: block;
clear: both;
}
.img-box {
display: inline-block;
width: 120px;
height: 120px;
position: relative;
margin-right: 10px;
&:hover .icon-group {
display: block;
}
&>img {
width: 100%;
height: 100%;
border-radius: 6px;
}
.icon-group {
width: 120px;
height: 120px;
line-height: 120px;
background: rgba(0, 0, 0, 0.5);
border-radius: 6px;
display: none;
position: absolute;
text-align: center;
top: 0;
left: 0;
i {
cursor: pointer;
color: #fff;
font-size: 24px;
}
}
}
}
.upload-box {
cursor: pointer;
border-radius: 6px;
border: 1px dashed #999;
width: 120px;
line-height: 120px;
height: 120px;
font-size: 24px;
text-align: center;
}
::v-deep .el-loading-spinner {
top: 0;
margin-top: 0;
}
.check {
margin-right: 20px;
}
</style>
vue 文件上传组件
最新推荐文章于 2024-05-15 22:30:02 发布