index.vue 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <template>
  2. <Uploader v-model="fileList" :max-count="1" :max-size="5 * 1024 * 1024" @oversize="onOversize" :after-read="afterRead"
  3. @delete="onDelete" />
  4. </template>
  5. <script lang="ts" setup>
  6. import { ref, PropType, watch } from 'vue'
  7. import { showFailToast, Uploader, UploaderFileListItem } from 'vant'
  8. import service from '@/services'
  9. import axios from 'axios'
  10. const props = defineProps({
  11. files: {
  12. type: Array as PropType<string[]>,
  13. default: () => ([])
  14. }
  15. })
  16. const emit = defineEmits(['success'])
  17. const fileList = ref<UploaderFileListItem[]>([])
  18. const onOversize = () => {
  19. showFailToast('图片大小不能超过 5Mb')
  20. }
  21. // eslint-disable-next-line
  22. const afterRead = (file: any) => {
  23. const data = new FormData()
  24. data.append('file', file.file)
  25. file.status = 'uploading'
  26. file.message = '上传中...'
  27. axios.post(service.getConfig('uploadUrl'), data).then(res => {
  28. if (res.status == 200) {
  29. file.status = 'success'
  30. file.message = '上传成功'
  31. if (res.data.length) {
  32. emit('success', res.data[0].filePath)
  33. }
  34. } else {
  35. file.status = 'failed'
  36. file.message = '上传失败'
  37. }
  38. })
  39. }
  40. const onDelete = () => {
  41. emit('success', '')
  42. }
  43. watch(() => props.files, () => {
  44. fileList.value = []
  45. props.files.forEach((url) => {
  46. fileList.value.push({
  47. url
  48. })
  49. })
  50. })
  51. </script>