index.vue 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <template>
  2. <input class="el-upload__input" ref="reffile" name="file" @change="fileChange($event)" :accept="$props.accept" type="file">
  3. <el-button icon="ele-Upload" @click="onClick">{{$props.btnText}}</el-button>
  4. </template>
  5. <script setup lang="ts" name="ImportButton">
  6. import { reactive, ref, onMounted, watch } from 'vue';
  7. import request,{request2} from '/@/utils/request';
  8. import { ElMessage } from 'element-plus';
  9. // 定义父组件传过来的值
  10. const props = defineProps({
  11. accept: {
  12. type: String,
  13. },
  14. param: {
  15. type: Object,
  16. default: () => {},
  17. },
  18. url: {
  19. type: String,
  20. },
  21. btnText: {
  22. type: String,
  23. },
  24. });
  25. // 定义子组件向父组件传值/事件
  26. const emit = defineEmits(['success', 'error']);
  27. const reffile=ref();
  28. // 定义变量内容
  29. const state = reactive({
  30. form: {} as any,
  31. });
  32. watch(
  33. () => props.param,
  34. (value) => {
  35. if (value) {
  36. state.form = Object.assign({}, { ...value });
  37. }
  38. },
  39. {
  40. immediate: true,
  41. deep: true,
  42. }
  43. );
  44. // 上传文件
  45. const onClick = () => {
  46. reffile.value.click();
  47. };
  48. function fileChange(event) {
  49. if(!event.currentTarget.files
  50. || event.currentTarget.files.length==0){
  51. return;
  52. }
  53. var file=event.currentTarget.files[0];
  54. let formData = new FormData()
  55. formData.append('file', file)
  56. for (const key in state.form) {
  57. const element = state.form[key];
  58. formData.append(key, element)
  59. }
  60. request2({
  61. url: props.url,
  62. method: 'post',
  63. data:formData,
  64. headers: {
  65. 'Content-Type': 'multipart/form-data'
  66. },
  67. }).then((res)=>{
  68. console.log(res);
  69. ElMessage.success(res);
  70. reffile.value.files=null;
  71. emit('success',res)
  72. }).catch((res)=>{
  73. console.log('上传错误',res)
  74. alert('上传错误')
  75. });
  76. }
  77. // 页面加载时
  78. onMounted(() => {
  79. // initFormField();
  80. });
  81. </script>