imgUpload.vue 2.2 KB

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