imgUpload.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <template>
  2. <ele-image-upload
  3. v-model="images"
  4. :limit="limit"
  5. :drag="true"
  6. :multiple="true"
  7. :upload-handler="uploadHandler"
  8. :beforeUpload="beforeUpload"
  9. @upload="onUpload"
  10. >
  11. </ele-image-upload>
  12. </template>
  13. <script>
  14. import EleImageUpload from 'ele-admin/es/ele-image-upload';
  15. import { getImageUrl, getImagePath } from '@/utils/file';
  16. import { uploadFile } from '@/api/system/file/index';
  17. export default {
  18. components: { EleImageUpload },
  19. props: {
  20. // 所属模块
  21. module: {
  22. type: String,
  23. default: 'main'
  24. },
  25. // 限制数量
  26. limit: {
  27. type: Number,
  28. default: -1
  29. },
  30. value: {
  31. type: Array,
  32. default: () => []
  33. }
  34. },
  35. data () {
  36. return {};
  37. },
  38. computed: {
  39. images: {
  40. set (val) {
  41. this.$emit(
  42. 'input',
  43. val.map((item) => ({
  44. ...item,
  45. url: getImagePath(item.url)
  46. }))
  47. );
  48. },
  49. get () {
  50. const arr =
  51. (this.value &&
  52. this.value.map((item) => ({
  53. ...item,
  54. url: getImageUrl(item.url)
  55. }))) ||
  56. [];
  57. return arr;
  58. }
  59. }
  60. },
  61. methods: {
  62. // beforeUpload(){},
  63. /* 上传事件 */
  64. uploadHandler (file) {
  65. const item = {
  66. file,
  67. uid: file.uid,
  68. name: file.name,
  69. progress: 0,
  70. status: null
  71. };
  72. if (!file.type.startsWith('image')) {
  73. this.$message.error('只能选择图片');
  74. return;
  75. }
  76. if (file.size / 1024 / 1024 > 2) {
  77. this.$message.error('大小不能超过 2MB');
  78. return;
  79. }
  80. this.$emit('input', [...this.value, item]);
  81. this.onUpload(item);
  82. },
  83. /* 上传 item */
  84. async onUpload (item) {
  85. // 模拟上传
  86. item.status = 'uploading';
  87. item.progress = 20;
  88. const res = await uploadFile({
  89. module: this.module,
  90. multiPartFile: item.file
  91. });
  92. if (res.data) {
  93. item.url = res.data.storePath;
  94. item.id = res.data.id;
  95. item.progress === 100;
  96. item.status = 'done';
  97. }
  98. }
  99. }
  100. };
  101. </script>