index.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <template>
  2. <u-upload v-bind="$attrs" :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :notFile="notFile"
  3. :disabled="disabled">
  4. </u-upload>
  5. <view class="tips" v-if="tips">{{tips}}</view>
  6. </template>
  7. <script setup name="cyUpload">
  8. import {
  9. watch,
  10. ref
  11. } from 'vue';
  12. import baseUrl from '@/config/request.js';
  13. const emit = defineEmits(['update:filename', 'update:keyValue', 'success'])
  14. const props = defineProps({
  15. filename: {
  16. type: [Array, String],
  17. default: () => []
  18. },
  19. url: {
  20. type: String
  21. },
  22. notFile: {
  23. type: Boolean,
  24. default: false
  25. },
  26. tips: {
  27. type: String
  28. },
  29. disabled: {
  30. type: Boolean,
  31. default: false
  32. },
  33. isUpdate: {
  34. type: Boolean,
  35. default: false
  36. }
  37. })
  38. const fileList = ref([])
  39. watch(() => props.filename, (filename) => {
  40. if (!filename) return fileList.value = []
  41. if (typeof filename == 'string') {
  42. fileList.value = filename.split(',').map(v => ({
  43. url: baseUrl + v,
  44. }))
  45. } else {
  46. fileList.value = filename && filename.length > 0 ? filename.map(v => ({
  47. url: v.url || v,
  48. })) : []
  49. }
  50. }, {
  51. immediate: true,
  52. deep: true
  53. })
  54. const afterRead = async (e) => {
  55. const {
  56. file
  57. } = e
  58. fileList.value.push({
  59. ...file,
  60. status: 'uploading',
  61. message: '上传中...',
  62. });
  63. const result = await uploadFilePromise(file.url);
  64. console.log(result, 'result')
  65. fileList.value.forEach(v => {
  66. v.url = result.url
  67. v.status = 'success'
  68. v.message = ''
  69. })
  70. //更新外部参数
  71. emit('update:filename', fileList.value.map(v => v.url))
  72. emit('success', result)
  73. }
  74. const deletePic = (event) => {
  75. fileList.value.splice(event.index, 1);
  76. }
  77. const uploadFilePromise = (url, baseStr = '/common/upload') => {
  78. let token = uni.getStorageSync('token')
  79. return new Promise((resolve, reject) => {
  80. let a = uni.uploadFile({
  81. url: baseUrl + baseStr, // 图片上传地址
  82. filePath: url,
  83. name: 'file',
  84. header: {
  85. "Authorization": token
  86. },
  87. success: (res) => {
  88. let respic = JSON.parse(res.data)
  89. resolve(respic)
  90. },
  91. });
  92. });
  93. };
  94. </script>
  95. <style lang="scss" scoped>
  96. .tips {
  97. font-size: 24rpx;
  98. font-family: PingFangSC, PingFang SC;
  99. font-weight: 400;
  100. color: #969696;
  101. line-height: 48rpx;
  102. margin-top: 10rpx;
  103. }
  104. ::v-deep .align-right .u-upload__wrap {
  105. justify-content: flex-end;
  106. }
  107. </style>