PicUploader.vue 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <script setup lang="ts">
  2. import { uploadFileOld } from '@/api/file'
  3. import { ref, watch } from 'vue'
  4. import type { UploadFile } from 'tdesign-vue-next'
  5. // 接收 props
  6. const props = defineProps<{
  7. modelValue: string
  8. }>()
  9. // 定义 emit
  10. const emit = defineEmits<{
  11. 'update:modelValue': [string | undefined]
  12. }>()
  13. // 初始化 fileList,根据 props.modalValue 来判断
  14. const fileList = ref<UploadFile[]>(props.modelValue ? [{ url: props.modelValue }] : [])
  15. // 监听 fileList 的变化,并深度监听
  16. watch(fileList, () => {
  17. // 确保 fileList 不为空,并且有文件
  18. if (fileList.value.length > 0 && fileList.value[0].url) {
  19. emit('update:modelValue', fileList.value[0].url)
  20. } else {
  21. emit('update:modelValue', undefined) // 如果没有文件,发送 undefined
  22. }
  23. }, { deep: true })
  24. watch(() => props.modelValue, (value) => {
  25. if (value) {
  26. fileList.value = [{ url: value }]
  27. } else {
  28. fileList.value = []
  29. }
  30. })
  31. </script>
  32. <template>
  33. <TUpload theme="image" accept="image/jpeg,image/png" :request-method="uploadFileOld" v-model="fileList">
  34. </TUpload>
  35. </template>
  36. <style scoped>
  37. </style>