Without further ado, let’s start with the secondary encapsulation el-upload code.
<template> <div> <el-upload class="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>
Note: 1. When "auto-upload" is set to false, beforeUpload, onSuccess, before-upload, and on-success will not be triggered. At this time, only on-change will be triggered;
2. When "limit" is set to 1, on-change is triggered once, and on-change will change as the limit changes. In addition, when the uploaded file exceeds the limit, the on-exceed method will be triggered;