CustomUploadComp.vue 2.35 KB
<script setup name="CustomUploadComp" lang="ts">
  import { PlusOutlined, CloseCircleOutlined } from '@ant-design/icons-vue';
  import { Upload, Spin } from 'ant-design-vue';
  import { ref, watchEffect } from 'vue';
  import { useUpload } from './hooks/useUploadFile.hook';
  import { logoUpload } from '/@/api/oem';

  const props = withDefaults(
    defineProps<{
      imgUrl: string;
    }>(),
    {
      imgUrl: '',
    }
  );
  const emit = defineEmits(['setImg']);

  const { beforeUploadVerify } = useUpload();

  const uploadLoading = ref(false);

  const uploadImgUrl = ref('');

  //上传图片接口
  const customUpload = async ({ file }) => {
    try {
      if (beforeUploadVerify(file)) {
        uploadImgUrl.value = '';
        uploadLoading.value = true;
        const formData = new FormData();
        formData.append('file', file);
        const response = await logoUpload(formData);
        if (response.fileStaticUri) {
          uploadImgUrl.value = response.fileStaticUri;
          emit('setImg', uploadImgUrl.value);
        }
      }
    } finally {
      uploadLoading.value = false;
    }
  };

  // 删除图片
  const handleDelete = () => {
    uploadImgUrl.value = '';
    emit('setImg', uploadImgUrl.value);
  };

  watchEffect(() => {
    init();
  });
  function init() {
    if (!props.imgUrl) uploadImgUrl.value = '';
    uploadImgUrl.value = props.imgUrl;
  }
</script>

<template>
  <div>
    <Upload
      name="avatar"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :customRequest="customUpload"
      :before-upload="beforeUploadVerify"
    >
      <div v-if="uploadImgUrl" class="w-full h-full modal-div relative">
        <img class="fill-img" :src="uploadImgUrl" alt="avatar" />
        <CloseCircleOutlined class="absolute icon-delete" @click.stop="handleDelete" />
      </div>
      <div v-else>
        <Spin v-if="uploadLoading" tip="正在上传中..." />
        <PlusOutlined v-else />
        <div class="ant-upload-text">上传</div>
      </div>
    </Upload>
  </div>
</template>

<style lang="less" scoped>
  .fill-img {
    width: 100%;
    height: 100%;
  }

  .icon-delete {
    top: -13px;
    right: -13px;
    color: rgb(146, 145, 145);
    font-size: 1rem;
    z-index: 9999;
  }
</style>