Imgs.vue 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <template>
  2. <div class="upload-box">
  3. <el-upload
  4. v-model:file-list="_fileList"
  5. action="#"
  6. list-type="picture-card"
  7. :class="['upload', self_disabled ? 'disabled' : '', drag ? 'no-border' : '']"
  8. :multiple="true"
  9. :disabled="self_disabled"
  10. :limit="limit"
  11. :http-request="handleHttpUpload"
  12. :before-upload="beforeUpload"
  13. :on-exceed="handleExceed"
  14. :on-success="uploadSuccess"
  15. :on-error="uploadError"
  16. :drag="drag"
  17. :accept="fileType.join(',')"
  18. >
  19. <div class="upload-empty">
  20. <slot name="empty">
  21. <el-icon><Plus /></el-icon>
  22. <!-- <span>请上传图片</span> -->
  23. </slot>
  24. </div>
  25. <template #file="{ file }">
  26. <img :src="file.url" class="upload-image" />
  27. <div class="upload-handle" @click.stop>
  28. <div class="handle-icon" @click="handlePictureCardPreview(file)">
  29. <el-icon><ZoomIn /></el-icon>
  30. <span>查看</span>
  31. </div>
  32. <div v-if="!self_disabled" class="handle-icon" @click="handleRemove(file)">
  33. <el-icon><Delete /></el-icon>
  34. <span>删除</span>
  35. </div>
  36. </div>
  37. </template>
  38. </el-upload>
  39. <div class="el-upload__tip">
  40. <slot name="tip"></slot>
  41. </div>
  42. <el-image-viewer v-if="imgViewVisible" :url-list="[viewImageUrl]" @close="imgViewVisible = false" />
  43. </div>
  44. </template>
  45. <script setup lang="ts" name="UploadImgs">
  46. import { ref, computed, inject, watch } from "vue";
  47. import { Plus } from "@element-plus/icons-vue";
  48. import { uploadImg } from "@/api/modules/upload";
  49. import type { UploadProps, UploadFile, UploadUserFile, UploadRequestOptions } from "element-plus";
  50. import { ElNotification, formContextKey, formItemContextKey } from "element-plus";
  51. interface UploadFileProps {
  52. fileList: UploadUserFile[];
  53. api?: (params: any) => Promise<any>; // 上传图片的 api 方法,一般项目上传都是同一个 api 方法,在组件里直接引入即可 ==> 非必传
  54. drag?: boolean; // 是否支持拖拽上传 ==> 非必传(默认为 true)
  55. disabled?: boolean; // 是否禁用上传组件 ==> 非必传(默认为 false)
  56. limit?: number; // 最大图片上传数 ==> 非必传(默认为 5张)
  57. fileSize?: number; // 图片大小限制 ==> 非必传(默认为 5M)
  58. fileType?: File.ImageMimeType[]; // 图片类型限制 ==> 非必传(默认为 ["image/jpeg", "image/png", "image/gif"])
  59. height?: string; // 组件高度 ==> 非必传(默认为 150px)
  60. width?: string; // 组件宽度 ==> 非必传(默认为 150px)
  61. borderRadius?: string; // 组件边框圆角 ==> 非必传(默认为 8px)
  62. }
  63. const props = withDefaults(defineProps<UploadFileProps>(), {
  64. fileList: () => [],
  65. drag: true,
  66. disabled: false,
  67. limit: 5,
  68. fileSize: 5,
  69. fileType: () => ["image/jpeg", "image/png", "image/gif"],
  70. height: "150px",
  71. width: "150px",
  72. borderRadius: "8px"
  73. });
  74. // 获取 el-form 组件上下文
  75. const formContext = inject(formContextKey, void 0);
  76. // 获取 el-form-item 组件上下文
  77. const formItemContext = inject(formItemContextKey, void 0);
  78. // 判断是否禁用上传和删除
  79. const self_disabled = computed(() => {
  80. return props.disabled || formContext?.disabled;
  81. });
  82. const _fileList = ref<UploadUserFile[]>(props.fileList);
  83. // 监听 props.fileList 列表默认值改变
  84. watch(
  85. () => props.fileList,
  86. (n: UploadUserFile[]) => {
  87. _fileList.value = n;
  88. }
  89. );
  90. /**
  91. * @description 文件上传之前判断
  92. * @param rawFile 选择的文件
  93. * */
  94. const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  95. const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;
  96. const imgType = props.fileType.includes(rawFile.type as File.ImageMimeType);
  97. if (!imgType)
  98. ElNotification({
  99. title: "温馨提示",
  100. message: "上传图片不符合所需的格式!",
  101. type: "warning"
  102. });
  103. if (!imgSize)
  104. setTimeout(() => {
  105. ElNotification({
  106. title: "温馨提示",
  107. message: `上传图片大小不能超过 ${props.fileSize}M!`,
  108. type: "warning"
  109. });
  110. }, 0);
  111. return imgType && imgSize;
  112. };
  113. /**
  114. * @description 图片上传
  115. * @param options upload 所有配置项
  116. * */
  117. const handleHttpUpload = async (options: UploadRequestOptions) => {
  118. let formData = new FormData();
  119. formData.append("file", options.file);
  120. try {
  121. const api = props.api ?? uploadImg;
  122. const { data } = await api(formData);
  123. options.onSuccess(data);
  124. } catch (error) {
  125. options.onError(error as any);
  126. }
  127. };
  128. /**
  129. * @description 图片上传成功
  130. * @param response 上传响应结果
  131. * @param uploadFile 上传的文件
  132. * */
  133. const emit = defineEmits<{
  134. "update:fileList": [value: UploadUserFile[]];
  135. }>();
  136. const uploadSuccess = (response: { fileUrl: string } | undefined, uploadFile: UploadFile) => {
  137. if (!response) return;
  138. uploadFile.url = response.fileUrl;
  139. emit("update:fileList", _fileList.value);
  140. // 调用 el-form 内部的校验方法(可自动校验)
  141. formItemContext?.prop && formContext?.validateField([formItemContext.prop as string]);
  142. ElNotification({
  143. title: "温馨提示",
  144. message: "图片上传成功!",
  145. type: "success"
  146. });
  147. };
  148. /**
  149. * @description 删除图片
  150. * @param file 删除的文件
  151. * */
  152. const handleRemove = (file: UploadFile) => {
  153. _fileList.value = _fileList.value.filter(item => item.url !== file.url || item.name !== file.name);
  154. emit("update:fileList", _fileList.value);
  155. };
  156. /**
  157. * @description 图片上传错误
  158. * */
  159. const uploadError = () => {
  160. ElNotification({
  161. title: "温馨提示",
  162. message: "图片上传失败,请您重新上传!",
  163. type: "error"
  164. });
  165. };
  166. /**
  167. * @description 文件数超出
  168. * */
  169. const handleExceed = () => {
  170. ElNotification({
  171. title: "温馨提示",
  172. message: `当前最多只能上传 ${props.limit} 张图片,请移除后上传!`,
  173. type: "warning"
  174. });
  175. };
  176. /**
  177. * @description 图片预览
  178. * @param file 预览的文件
  179. * */
  180. const viewImageUrl = ref("");
  181. const imgViewVisible = ref(false);
  182. const handlePictureCardPreview: UploadProps["onPreview"] = file => {
  183. viewImageUrl.value = file.url!;
  184. imgViewVisible.value = true;
  185. };
  186. </script>
  187. <style scoped lang="scss">
  188. .is-error {
  189. .upload {
  190. :deep(.el-upload--picture-card),
  191. :deep(.el-upload-dragger) {
  192. border: 1px dashed var(--el-color-danger) !important;
  193. &:hover {
  194. border-color: var(--el-color-primary) !important;
  195. }
  196. }
  197. }
  198. }
  199. :deep(.disabled) {
  200. .el-upload--picture-card,
  201. .el-upload-dragger {
  202. cursor: not-allowed;
  203. background: var(--el-disabled-bg-color) !important;
  204. border: 1px dashed var(--el-border-color-darker);
  205. &:hover {
  206. border-color: var(--el-border-color-darker) !important;
  207. }
  208. }
  209. }
  210. .upload-box {
  211. .no-border {
  212. :deep(.el-upload--picture-card) {
  213. border: none !important;
  214. }
  215. }
  216. :deep(.upload) {
  217. .el-upload-dragger {
  218. display: flex;
  219. align-items: center;
  220. justify-content: center;
  221. width: 100%;
  222. height: 100%;
  223. padding: 0;
  224. overflow: hidden;
  225. border: 1px dashed var(--el-border-color-darker);
  226. border-radius: v-bind(borderRadius);
  227. &:hover {
  228. border: 1px dashed var(--el-color-primary);
  229. }
  230. }
  231. .el-upload-dragger.is-dragover {
  232. background-color: var(--el-color-primary-light-9);
  233. border: 2px dashed var(--el-color-primary) !important;
  234. }
  235. .el-upload-list__item,
  236. .el-upload--picture-card {
  237. width: v-bind(width);
  238. height: v-bind(height);
  239. background-color: transparent;
  240. border-radius: v-bind(borderRadius);
  241. }
  242. .upload-image {
  243. width: 100%;
  244. height: 100%;
  245. object-fit: contain;
  246. }
  247. .upload-handle {
  248. position: absolute;
  249. top: 0;
  250. right: 0;
  251. box-sizing: border-box;
  252. display: flex;
  253. align-items: center;
  254. justify-content: center;
  255. width: 100%;
  256. height: 100%;
  257. cursor: pointer;
  258. background: rgb(0 0 0 / 60%);
  259. opacity: 0;
  260. transition: var(--el-transition-duration-fast);
  261. .handle-icon {
  262. display: flex;
  263. flex-direction: column;
  264. align-items: center;
  265. justify-content: center;
  266. padding: 0 6%;
  267. color: aliceblue;
  268. .el-icon {
  269. margin-bottom: 15%;
  270. font-size: 140%;
  271. }
  272. span {
  273. font-size: 100%;
  274. }
  275. }
  276. }
  277. .el-upload-list__item {
  278. &:hover {
  279. .upload-handle {
  280. opacity: 1;
  281. }
  282. }
  283. }
  284. .upload-empty {
  285. display: flex;
  286. flex-direction: column;
  287. align-items: center;
  288. font-size: 12px;
  289. line-height: 30px;
  290. color: var(--el-color-info);
  291. .el-icon {
  292. font-size: 28px;
  293. color: var(--el-text-color-secondary);
  294. }
  295. }
  296. }
  297. .el-upload__tip {
  298. line-height: 15px;
  299. text-align: center;
  300. }
  301. }
  302. </style>