做项目要上传图片,用到的地方比较多,就封装了组件,用了element-ui的upload,并且根据limit来限制上传的张数,超出部分隐藏,还有父子组件传值,传给后台的样式是数组形式。话不多数,贴上代码,加油各位!!
组件代码
HTML代码
如下:
<template>
<div class="about">
<el-upload
:class="{hide:hideUpload}"
action="后台上传地址"
list-type="picture-card"
name="image"
:data="{type:type}"
:limit="limit"
:before-remove="beforeRemove"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-success="handleAvatarSuccess"
:on-change="handChange"
:headers="headers"
:file-list="pics"
>
<i class="el-icon-plus"></i>
<div v-if="hideLimit" class="el-upload__tip" slot="tip">
<span>可批量上传,最多上传{{limit}}张</span>
</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt />
</el-dialog>
</div>
</template>
js代码
如下:
<script>
export default {
props: ["limit", "type", "pic"],
data() {
return {
hideUpload: false,
token: store.state.token,
dialogImageUrl: "",
dialogVisible: false,
imgUrl: [],
arr: [],
headers: { Authorization: "Bearer " + localStorage.getItem("token")},
hideLimit: true,
pics: []
};
},
mounted() {
let _this = this;
setTimeout(function() {
if (_this.pic) {
_this.pics = _this.pic;
_this.hideUpload = _this.pic.length >= _this.limit;
_this.getArr(_this.pic);
}
if (_this.type == "room" || _this.type == "house") {
_this.hideLimit = false;
}
}, 500);
},
methods: {
beforeRemove(file, fileList){
console.log(file, fileList)
},
handleRemove(file, fileList) {
console.log(file, fileList)
Array.prototype.remove = function(val) {
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};
this.arr.remove(file.id);
this.hideUpload = fileList.length >= this.limit;
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
handleAvatarSuccess(res) {
if (this.pic) {
this.imgUrl = this.pic;
}
this.imgUrl.push(res.id);
this.$emit("imgUrlarr", this.imgUrl);
},
handChange(file, fileList) {
this.hideUpload = fileList.length >= this.limit;
},
//把json转数组,只存储id,方便传给后台
getArr(item) {
console.log(item);
let arr = [];
if (item) {
item.forEach(function(item) {
arr.push(item.id);
});
}
console.log(arr);
this.arr = arr;
this.$emit("imgUrlarr", this.arr);
}
}
};
</script>
css
如下:
<style lang="scss">
.hide .el-upload--picture-card {
display: none;
}
.img {
width: 148px;
height: 148px;
display: flex;
img {
width: 100%;
height: 100%;
margin-right: 10px;
}
}
</style>
引入文件的代码
应用组件
<upload-img @imgUrlarr="getImg" :pic="lockingfrom.pics" :type="type" :limit="2"></upload-img>
js
<script>
import uploadImg from "@/components/uploadImg";
export default{
components: {uploadImg},
data(){
return{
type: "customer",
lockingfrom: {
pics: ""
},
}
},
methods:{
getImg(e) {
this.lockingfrom.pics = e;
},
}
}
</script>