index.vue 2.31 KB
<template>
  <Upload :accept="accept" :custom-request="onUpload" :file-list="[]" :show-file-list="false">
    <template #upload-button>
      <div class="arco-upload-list-item">
        <Image
          v-if="modelValue"
          :style="{ minHeight }"
          :width="width"
          :height="height"
          :preview="false"
          :src="modelValue"
          :fit="fit"
          show-loader
        />
        <div v-else :style="style" class="arco-upload-picture-card">
          <div class="arco-upload-picture-card-text">
            <IconPlus />
          </div>
        </div>
      </div>
    </template>
  </Upload>
</template>

<script lang="ts" setup>
  import useOss from '@/hooks/oss';
  import { computed } from 'vue';
  import { IconPlus } from '@arco-design/web-vue/es/icon';
  import { UploadRequest, useFormItem, Upload, Image } from '@arco-design/web-vue';

  type PropType = {
    modelValue?: string;
    accept?: string;
    width?: number | string;
    height?: number | string;
    minHeight?: string;
    fit?: 'none' | 'contain' | 'cover' | 'fill' | 'scale-down' | undefined;
  };

  const props = withDefaults(defineProps<PropType>(), {
    modelValue: '',
    accept: 'image/*',
    width: 80,
    height: 'auto',
    minHeight: '100%',
    fit: 'cover',
  });

  const emits = defineEmits(['update:modelValue']);
  const { eventHandlers } = useFormItem();

  const style = computed(() => {
    return {
      width: `${props.width}px`,
      height: props.height.constructor === String ? 'auto' : `${props.height}px`,
      maxWidth: '100%',
      maxHeight: '100%',
      minHeight: '80px',
    };
  });

  const { upload } = useOss();

  const onUpload = (option: any): UploadRequest => {
    const { fileItem } = option;

    if (fileItem.file) {
      upload(fileItem.file, 'image').then((res) => {
        emits('update:modelValue', res?.url || '');
        eventHandlers.value?.onChange?.();
      });
    }

    return {};
  };
</script>

<style lang="less" scoped>
  :deep(.arco-avatar-text) {
    width: 100%;
    height: 100%;
  }

  :deep(.arco-upload-list-item) {
    margin-top: 0 !important;
  }

  .no-avatar {
    position: absolute;
    display: flex;
    align-content: center;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
  }
</style>