index.vue 2.08 KB
<script lang="ts" setup name="SelectImage">
import { FormItemRest, Upload } from 'ant-design-vue'
import { Icon } from '@iconify/vue'
import { computed } from 'vue'
import ImageSelectorModal from './ImageSelectorModal.vue'
import { type ImageSelectorDataType } from '.'
import { useModal } from '@/components/Modal'
import { VariableImageSourceEnum } from '@/enums/datasource'
import { useTranslation } from '@/hooks/useTranslation'

const props = defineProps<{
  value?: ImageSelectorDataType
}>()

const emits = defineEmits(['register', 'update:value'])
const { t } = useTranslation()
const [register, { openModal }] = useModal()

const getImageSrc = computed(() => {
  const { libPath = '', imageSource, path } = props.value || {}
  if (libPath || path)
    return imageSource === VariableImageSourceEnum.LOCAL ? path : libPath
  return ''
})

const handleOpenSelectModal = () => {
  openModal(true, props.value)
}

const handleSelectComplete = (record: ImageSelectorDataType) => {
  emits('update:value', { ...record })
}
</script>

<template>
  <Upload class="image-selector rounded-lg" v-bind="$attrs" list-type="picture-card" :open-file-dialog-on-click="false">
    <main class="w-full h-full p-2 box-border" @click="handleOpenSelectModal">
      <img v-if="getImageSrc" :src="getImageSrc" alt="avatar" class="w-full h-full">
      <div v-else class="w-full h-full flex justify-center items-center flex-col rounded-lg">
        <Icon icon="ant-design:plus-outlined" class="cursor-pointer svg:text-lg" />
        <div class="ant-upload-text">
          {{ t('clickDownload') }}
        </div>
      </div>
    </main>
  </Upload>
  <FormItemRest>
    <ImageSelectorModal @register="register" @select-complete="handleSelectComplete" />
  </FormItemRest>
</template>

<style lang="less" scoped>
.image-selector.ant-upload-picture-card-wrapper {
  width: 100px;
  height: 100px;
  box-sizing: border-box;

  :deep(.ant-upload-wrapper) {
    width: 100px;
    height: 100px;
  }

  :deep(.ant-upload.ant-upload-select-picture-card) {
    margin: 0;
    width: 100px;
    height: 100px;
    box-sizing: border-box;
  }

}
</style>