在时间开发中,在上传图片时可能有各种各样的需求,比如上传组件中间的文字自定义、上传图片提示文字,但是element提供的上传组件比较基础,所以在此将完善后的内容表达出来。
最终效果如图所示:
对于组件的基本导入等步骤在此省略,直接使用~
1.html代码
<div class="upload"> <el-upload accept="image/jpg,image/jpeg,image/gif,image/png" action="https://furen.com/sysFileInfo/upload" class="upload-box" :file-list="imageList" list-type="picture-card" multiple :before-upload="beforeAvatarUpload" :on-remove="handelRemove" :on-success="handleAvatarSuccess" style="display: flex; align-items: flex-end" > <el-icon class="avatar-uploader-icon"> // 组件中间的文字内容 <Plus /> <div>+</div> <span>上传图片</span> </el-icon> <template #tip> <div class="el-upload__tip">图片大小不超过20MB</div> // 上传提示 </template> </el-upload> </div>
2.css代码
.upload { .upload-box { margin-bottom: 20px; .el-upload-list { &.el-upload-list--picture-card { min-height: 120px; max-width: 520px; } } .el-upload { &.el-upload--picture-card { width: 120px; height: 120px; } } .el-upload-list__item-actions { width: 120px; height: 120px; } .el-upload-list__item { &.is-success { width: 120px; height: 120px; } } .el-upload-list__item-thumbnail { width: 120px; height: 120px; } } .el-icon.avatar-uploader-icon { width: 80px; display: flex; flex-direction: column; align-items: center; span { color: #999; font-size: 14px; font-style: normal; } } .el-upload__tip { margin-left: 10px; color: #999; } .el-input { width: 120px; } :deep(.el-upload-list) { .is-success { overflow: hidden; height: auto; width: 192px; border: 0; border-radius: 0; margin-right: 10px; img, .el-upload-list__item-actions { height: 108px; } .el-input { .el-input__inner { height: 32px; } } } .is-ready, .is-uploading { display: none; } } :deep(.el-upload) { width: 192px; height: 108px; line-height: 108px; background: transparent; border: 1px solid #dcdfe6; border-radius: 0; margin-bottom: 20px; .el-icon-plus { color: #dcdfe6; font-size: 24px; } } }
3.js代码
const state = reactive({ professionalQua:[], )} // 图片上传前拦截方法(限制图片格式和大小) const beforeAvatarUpload = (file) => { const type = ['image/jpeg', 'image/jpg', 'image/png', 'image/svg'] const isJPG = type.includes(file.type) const isLt20M = file.size / 1024 / 1024 < 20 if (!isJPG) { ElMessage({ message: '图片格式错误', type: 'error', }) } if (!isLt20M) { ElMessage({ message: '上传图片不能超过20M', type: 'error', }) } return isJPG && isLt20M } // 图片上传成功返回图片地址方法 const handleAvatarSuccess = (res) => { const name = file.name.split('.')[0] // 上传图片的名称 if (res.code == 200) { const path = res.data && res.data.filePath // 图片地址 state.professionalQua.push({ // 将图片名称和地址一起存在一个数组中 urlPath: path, contentName: name, }) } } // 移除图片方法(根据名称找到对应移除的图片的索引,然后把其从数组中删除) const handelRemove = (file) => { const name = file.name.split('.')[0] const index = state.formData.professionalQua.findIndex( (r) => r.contentName == name ) state.professionalQua.splice(index, 1) }
以上代码就实现了一个可以上传多张图片的一个效果,上传多图片后效果如下: