图片回显时隐藏上传区域,鼠标悬浮显示遮罩层进行编辑、删除操作,删除图片后显示上传区域
vue部分:
①el-upload没有限制上传文件数量,如果limit=1,那么点击编辑时不会触发on-change事件,需要先清除当前文件,页面会出现上传区域;
②删除按钮click.stop阻止事件冒泡,删除后不会弹出上传图片窗口
<template>
<el-upload class="upload-demo" drag action="#" accept=".jpg,.png" :on-change="handleChange" :auto-upload="false"
ref="uploadRef" :show-file-list="false">
<!-- 图片上传框 -->
<div v-if="!fileList.length">
<el-icon class="el-icon--upload"><upload-filled /></el-icon>
<div class="el-upload__text">
Drop file here or <em>click to upload</em>
</div>
</div>
<!-- 回显及遮罩层 -->
<div v-else>
<img :src="fileList[0].url" alt="">
<div class="mask">
<el-icon size="50">
<Edit />
</el-icon>
<el-icon size="50" @click.stop="handleDelete">
<Delete />
</el-icon>
</div>
</div>
<template #tip>
<div class="el-upload__tip tip">
jpg/png files with a size less than 500kb
</div>
</template>
</el-upload>
</template>
ts部分:
<script setup lang="ts">
import { ref } from 'vue'
import type { UploadFile, UploadUserFile } from 'element-plus'
let fileList = ref<UploadUserFile[]>([])
const uploadRef = ref()
const handleChange = (file: UploadFile) => {
//如果上传的图片没有url字段,手动生成
if (!file.url) file.url = URL.createObjectURL(file.raw as any)
fileList.value[0] = file
}
const handleDelete = () => {
//删除时清除所有已上传图片
uploadRef.value.clearFiles()
fileList.value = []
}
</script>
样式:
<style lang="scss" scoped>
:deep(.el-upload) {
height: 100%;
}
:deep(.el-upload-dragger) {
height: 100%;
padding: 10px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
box-sizing: border-box;
}
.upload-demo {
width: 300px;
height: 200px;
}
.tip {
color: red;
}
//遮罩层
.mask {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(100, 100, 100, 0.5);
color: #ffffff;
opacity: 0;
display: flex;
justify-content: center;
align-items: center;
&:hover {
opacity: 1;
}
.el-icon {
margin: 0 10px;
&:hover {
color: #70aeed;
}
}
}
</style>