因为不满足于element ui的默认图片上传功能自己改造了一款头像上传和一款图片上传的组件
二.上传图片功能(支持多张图片哦~)
冰菓.png
下面附上代码
<template>
<div>
<el-card>
<p>轮子一·头像添加</p>
<el-upload
class="avatar-uploader"
action="http://apisrm.soolcool.com/sys/common/upload-pic"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:on-remove="handleRemove"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<span v-if="imageUrl" class="el-upload-action" @click.stop="handleRemove()">
<i class="el-icon-delete"></i>
</span>
<i v-else class="el-icon-upload2 avatar-uploader-icon" stop></i>
</el-upload>
</el-card>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: '',
files: []
}
},
methods: {
// 移除图片
handleRemove() {
this.files = []
this.imageUrl = ''
},
// 上传成功回调
handleAvatarSuccess(res, file) {
this.imageUrl = res.data.url
this.files.push(file)
},
// 上传前格式和图片大小限制
beforeAvatarUpload(file) {
const type = file.type === 'image/jpeg' || 'image/jpg' || 'image/webp' || 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!type) {
this.$message.error('图片格式不正确!(只能包含jpg,png,webp,JPEG)')
}
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!')
}
return type && isLt2M
}
}
}
</script>
<style scoped lang='less'>
.avatar-uploader{
width: 100PX;
height: 100px;
cursor: pointer;
position: relative;
overflow: hidden;
background-color: #eee;
}
.avatar-uploader-icon{
box-sizing: border-box;
font-size: 28px;
color: #b7b7b7;
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}
.avatar-uploader-icon:hover{
border: 1px dashed #b7b7b7;
color: #fff;
background-color: rgba(0, 0, 0, .3);
}
.avatar {
position: relative;
width: 100px;
height: 100px;
display: block;
}
.el-upload-action {
position: absolute;
top: 0;
left: 0;
display: block;
width: 100%;
height: 100%;
font-size: 0;
color: #fff;
text-align: center;
line-height: 100px;
}
.el-upload-action:hover {
font-size: 20px;
background-color: #000;
background-color: rgba(0, 0, 0, .3)
}
</style>