avatar.vue 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <template>
  2. <el-upload
  3. class="avatar-uploader"
  4. action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
  5. :show-file-list="false"
  6. :on-success="handleAvatarSuccess"
  7. :before-upload="beforeAvatarUpload"
  8. >
  9. <img v-if="imageUrl" :src="imageUrl" class="avatar" />
  10. <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  11. </el-upload>
  12. </template>
  13. <script lang="ts" setup>
  14. import { ref } from 'vue'
  15. import { ElMessage } from 'element-plus'
  16. import { Plus } from '@element-plus/icons-vue'
  17. import type { UploadProps } from 'element-plus'
  18. const imageUrl = ref('')
  19. const handleAvatarSuccess: UploadProps['onSuccess'] = (
  20. response,
  21. uploadFile
  22. ) => {
  23. imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  24. }
  25. const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  26. if (rawFile.type !== 'image/jpeg') {
  27. ElMessage.error('Avatar picture must be JPG format!')
  28. return false
  29. } else if (rawFile.size / 1024 / 1024 > 2) {
  30. ElMessage.error('Avatar picture size can not exceed 2MB!')
  31. return false
  32. }
  33. return true
  34. }
  35. </script>
  36. <style scoped>
  37. .avatar-uploader .avatar {
  38. width: 178px;
  39. height: 178px;
  40. display: block;
  41. }
  42. </style>
  43. <style>
  44. .avatar-uploader .el-upload {
  45. border: 1px dashed var(--el-border-color);
  46. border-radius: 6px;
  47. cursor: pointer;
  48. position: relative;
  49. overflow: hidden;
  50. transition: var(--el-transition-duration-fast);
  51. }
  52. .avatar-uploader .el-upload:hover {
  53. border-color: var(--el-color-primary);
  54. }
  55. .el-icon.avatar-uploader-icon {
  56. font-size: 28px;
  57. color: #8c939d;
  58. width: 178px;
  59. height: 178px;
  60. text-align: center;
  61. }
  62. </style>