样式
<!--
* @Author: czz
* @Date: 2022-05-05 11:27:11
* @LastEditTime: 2022-05-27 13:44:40
* 用法:传入url显示图片,绑定事件change返回对象包含图片文件和图片base64
-->
<template>
<div class="uploadCover">
<input type="file" @change="uploadChange($event)" ref="upload" accept="image/jpg, image/jpeg, image/png">
<div class="upload" @click="clickToUpload">
<div @click="lookImgs($event)" class="imgs" v-viewer v-show="img" :style="{opacity:loading?'0.5':'1'}">
<img :src="img" alt="">
<img id="img_del" src="../assets/[email protected]" alt="" @click="deleteImg($event)">
</div>
<div class="addImg" v-show="loading?true:img?false:true">
<a-spin :indicator="indicator" v-show="loading"/>
<img src="../assets/addImg.png" v-show="!loading" alt="图片不见了"><br>
<span v-if="!img">上传封面</span>
</div>
</div>
</div>
</template>
<script>
export default {
props:{
url:'',
},
data(){
return{
indicator: <a-icon type="loading" style="color:#aaa;font-size: 24px" spin />,
img:'',//图片url
file:null,
loading:false,
}
},
created(){
},
mounted(){
},
watch:{
url:{
immediate:true,
handler(newVal,oldVal){
this.img = newVal
},
deep:true,
}
},
methods:{
lookImgs(e){
e.stopPropagation()
// console.log(111);
},
//点击上传封面div
clickToUpload(e){
// console.log(e);
if(this.loading){
e.preventDefault()
}else{
//点击div触发input的点击事件
this.$refs.upload.click()
}
},
//点击删除图片
deleteImg(e){
e.stopPropagation()//阻止冒泡
if(!this.loading){
this.img = ''
this.$emit('delete',true)
}
},
//把图片转换成base64(用来临时显示)
getBase64(img, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
},
//上传图片change事件
uploadChange(e){
// console.log(e.target.files);
this.loading = true
if(e.target.files.length>0){
//选择图片继续执行
let filesArr = e.target.files
this.getBase64(filesArr[0],imageUrl=>{
// imgurl = imageUrl
this.img = imageUrl
this.file = filesArr[0]
let file = new FormData()
file.append("file",this.file)
this.loading = false
this.$emit('change',{filesArr:this.file,imgBase64:this.img,file:file})
this.$refs.upload.value = null;
})
}else{
//选择了“取消”
this.loading = false
}
},
}
}
</script>
<style lang="less">
.uploadCover{
width: 100%;
height: 100%;
input{
float: left;
opacity: 0;
width: 0;
}
.upload{
float: left;
z-index: 10;
margin-top: 0px;
margin-left: 0px;
// width: 504px;
// height: 285.25px;
width: 100%;
height: 100%;
box-sizing: normal;
padding: 2px;
cursor: pointer;
border: 1px dashed #ccc;
border-radius: 5px;
position: relative;
&:active{
opacity: 0.5;
}
.imgs{
width: 100%;
height: 100%;
position: relative;
img{
width: 100%;
height: 100%;
}
#img_del{
position: absolute;
right: 5px;
top: 5px;
font-size: 30px;
color: #fff;
border-radius: 50%;
background: #aaa;
width: 16px;
height: 16px;
}
}
.addImg{
width: 100px;
height: 50px;
position: absolute;
top: calc(50% - 25px);
left: calc(50% - 50px);
text-align: center;
img{
width: 24px;
height: 24px;
}
}
}
}
</style>