index.vue 2.3 KB

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