upload.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { defineComponent } from 'vue'
  2. import { Uploader, Button } from 'vant'
  3. import request from '@/helpers/request'
  4. export default defineComponent({
  5. name: 'Upload',
  6. props: {
  7. accept: {
  8. type: String
  9. },
  10. formatFile: {
  11. type: Function,
  12. default: (file: any) => file
  13. },
  14. 'onUpdate:modelValue': {
  15. type: Function,
  16. default: (val: any) => {}
  17. },
  18. disabled: {
  19. type: Boolean,
  20. default: false
  21. }
  22. },
  23. data() {
  24. return {
  25. list: [],
  26. uploading: false
  27. }
  28. },
  29. methods: {
  30. async beforeRead(file: File): Promise<boolean> {
  31. console.log('beforeRead', file)
  32. return true
  33. },
  34. async upload(file: File) {
  35. this.uploading = true
  36. const form = new FormData()
  37. form.append('file', file)
  38. try {
  39. const res = await request.post('/api-teacher/uploadFile', {
  40. data: form
  41. })
  42. this.$emit('update:modelValue', res.data.url)
  43. } catch (error) {}
  44. this.uploading = false
  45. }
  46. },
  47. render() {
  48. return (
  49. <Uploader
  50. accept={this.accept}
  51. maxCount={1}
  52. modelValue={this.list}
  53. disabled={this.disabled}
  54. beforeDelete={this.beforeRead}
  55. onUpdate:modelValue={async val => {
  56. if (val[0]) {
  57. await this.upload(val[0].file)
  58. this.formatFile(val[0].file)
  59. }
  60. this.list = val
  61. }}
  62. onDelete={() => {
  63. this.list = []
  64. this.$emit('update:modelValue', null)
  65. }}
  66. >
  67. <Button loading={this.uploading}>上传文件</Button>
  68. </Uploader>
  69. )
  70. }
  71. })