PluginImportForm.vue 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <template>
  2. <Dialog v-model="dialogVisible" title="插件导入" width="400">
  3. <el-upload
  4. ref="uploadRef"
  5. v-model:file-list="fileList"
  6. :action="importUrl + '?id=' + props.id"
  7. :auto-upload="false"
  8. :disabled="formLoading"
  9. :headers="uploadHeaders"
  10. :limit="1"
  11. :on-error="submitFormError"
  12. :on-exceed="handleExceed"
  13. :on-success="submitFormSuccess"
  14. accept=".jar"
  15. drag
  16. >
  17. <Icon icon="ep:upload" />
  18. <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
  19. </el-upload>
  20. <template #footer>
  21. <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
  22. <el-button @click="dialogVisible = false">取 消</el-button>
  23. </template>
  24. </Dialog>
  25. </template>
  26. <script lang="ts" setup>
  27. import { getAccessToken, getTenantId } from '@/utils/auth'
  28. defineOptions({ name: 'PluginImportForm' })
  29. const props = defineProps<{ id: number }>() // 接收 id 作为 props
  30. const message = useMessage() // 消息弹窗
  31. const dialogVisible = ref(false) // 弹窗的是否展示
  32. const formLoading = ref(false) // 表单的加载中
  33. const uploadRef = ref()
  34. const importUrl =
  35. import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/iot/plugin-config/upload-file'
  36. const uploadHeaders = ref() // 上传 Header 头
  37. const fileList = ref([]) // 文件列表
  38. /** 打开弹窗 */
  39. const open = () => {
  40. dialogVisible.value = true
  41. fileList.value = []
  42. resetForm()
  43. }
  44. defineExpose({ open }) // 提供 open 方法,用于打开弹窗
  45. /** 提交表单 */
  46. const submitForm = async () => {
  47. if (fileList.value.length == 0) {
  48. message.error('请上传文件')
  49. return
  50. }
  51. // 提交请求
  52. uploadHeaders.value = {
  53. Authorization: 'Bearer ' + getAccessToken(),
  54. 'tenant-id': getTenantId()
  55. }
  56. formLoading.value = true
  57. uploadRef.value!.submit()
  58. }
  59. /** 文件上传成功 */
  60. const emits = defineEmits(['success'])
  61. const submitFormSuccess = (response: any) => {
  62. if (response.code !== 0) {
  63. message.error(response.msg)
  64. formLoading.value = false
  65. return
  66. }
  67. message.alert('上传成功')
  68. formLoading.value = false
  69. dialogVisible.value = false
  70. // 发送操作成功的事件
  71. emits('success')
  72. }
  73. /** 上传错误提示 */
  74. const submitFormError = (): void => {
  75. message.error('上传失败,请您重新上传!')
  76. formLoading.value = false
  77. }
  78. /** 重置表单 */
  79. const resetForm = async (): Promise<void> => {
  80. // 重置上传状态和文件
  81. formLoading.value = false
  82. await nextTick()
  83. uploadRef.value?.clearFiles()
  84. }
  85. /** 文件数超出提示 */
  86. const handleExceed = (): void => {
  87. message.error('最多只能上传一个文件!')
  88. }
  89. </script>