?以上是没有上传的页面,以下是上传后鼠标放上去的效果
?与饿了么上传组件主要区别在于只会在一个图像占位符上操作
以下是上传图片组件代码内容
<template>
<div class="account-avatar">
<el-upload class="avatar-uploader" :action="uploadFileUrl" :show-file-list="false" :headers="headers" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
<i v-if="imageUrl" class="el-icon-plus avatar-uploader-icon iconClass"></i>
</el-upload>
</div>
</template>
<script>
import { getToken } from "@/utils/auth";
export default {
props: {
imgUrl: {
type: String,
default: ''
}
},
data() {
return {
certificateImg: [],
imageUrl: '',
uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
headers: {
Authorization: "Bearer " + getToken()
},
}
},
mounted() {
this.imageUrl = this.imgUrl
},
methods: {
handleAvatarSuccess(res, file) {
const fileName = file.name
this.imageUrl = file.response.url
this.$emit('fileUrl', this.imageUrl)
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg'
const isPNG = file.type === 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG && !isPNG) {
this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isJPG || (isPNG && isLt2M)
}
}
}
</script>
<style >
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
.iconClass{
position: absolute;
top: 0px;
left: 0px;
opacity: 0;
}
.iconClass:hover{
color: #fbfbfb;
position: absolute;
top: 0px;
left: 0px;
opacity: 0.5;
background-color: #7a7979;
}
</style>
引用组件内容代码
//vue中template部分
<el-form-item prop="issueCardPic" label-width="0">
<ImagesUpdate :imgUrl="form.issueCardPic" class="avatar-uploader"
@fileUrl="avatorUPload"></ImagesUpdate>
</el-form-item>
//vue中script部分
import ImagesUpdate from "@/views/components/imagesUpdate"; //附件组件的地址
export default {
data(){
return{
form:{}
...
}
},
components:{
ImagesUpdate
},
methods:{
avatorUPload(){
//上传后将地址塞入表单字段
this.$set(this.form, 'issueCardPic', val)
},
}
}