闲话少说,先上二次封装el-upload代码
<template><div><el-uploadclass="upload-demo"ref="uploadImgRef"action="#":show-file-list="false":auto-upload="false"accept=".png, .jpg, .gif":on-change="changeFile"><img v-if="fileUrl" class="img-class" :src="fileUrl" alt=""><el-button type="primary">选择文件</el-button></el-upload></div> </template><script lang="ts" setup> import { ref, watch } from "vue"; import { ElMessage } from "element-plus"; import type { UploadFile, ElUpload } from "element-plus";const props = defineProps({url: {type: String,default: ''} })const emits = defineEmits<{(e: "handleUpload", uploadFile: UploadFile, url: string): void; }>();const acceptedTypes = ['image/png', 'image/jpeg', 'image/gif'] const fileUrl = ref<string>('') const uploadImgRef = ref<InstanceType<typeof ElUpload> | null>(null);// 监听的作用,当用户编辑图片时,将图片展示再页面上 watch(() => props.url, (val) => {fileUrl.value = val }, { immediate: true })// 添加上传文件 const changeFile = async (file: UploadFile) => {const isAccepted = acceptedTypes.includes(file?.raw?.type as string)if (!isAccepted) { // 校验图片格式ElMessage.warning('上传的图片格式不符,请核查后重新上传,谢谢!')} else if (file.size && file.size > 1 * 1024 * 1024) { // 校验图片大小ElMessage.warning('图片大小不能超过1M,请核查后重新上传,谢谢!')} else {await checkResolution(file.raw) // 校验图片分辨率fileUrl.value = file.raw ? window.URL.createObjectURL(file.raw) : ''emits("handleUpload", file, fileUrl.value);} };// 校验图片分辨率为500*500 const checkResolution = (file: any) => {return new Promise((resolve, reject) => {const image = new Image()image.src = URL.createObjectURL(file)image.onload = () => {const width = image.width;const height = image.height;if (width === 500 && height === 500) {resolve(file)} else {ElMessage.warning('图片分辨率不符合要求,请核查后重新上传,谢谢!')// reject('图片分辨率不符合要求')}}}) }const handleClear = () => {uploadImgRef.value?.clearFiles(); };defineExpose({// uploadImgRef,handleClear, }); </script><style lang="scss" scoped> p {margin: 0;padding: 0;color: red; }.img-class {width: 100px;height: 100px;margin-right: 20px; }:deep(.el-upload) {display: flex;align-items: center;justify-content: left; } </style>
注意:1.当设置“auto-upload”为false时,beforeUpload、onSuccess、before-upload、on-success都不会触发,此时只会触发on-change;
2.当设置“limit”为1时,on-change之后触发一次,on-change会随 limit 改变而改变,另外,当上传的文件超过limit时,会触发on-exceed方法;