vue3.0 antdesginVue 单张图片上传(Upload ) 组件封装

<template>
  <a-upload
    v-model:file-list="fileList"
    :maxCount="1"
    :headers="{ authorization: 'authorization-text' }"
    :customRequest="customRequest"
    :beforeUpload="beforeUpload"
  >
    <a-button>
      <UploadOutlined></UploadOutlined>
      点击上传
    </a-button>
  </a-upload>
</template>
<script lang="ts" setup>
  import { ref, watch } from 'vue'
  import { message, Upload } from 'ant-design-vue'
  import type { UploadProps } from 'ant-design-vue'
  import { uploadFile } from '@/api/upload/index'//调用的api
  import { UploadOutlined } from '@ant-design/icons-vue'
  const props = withDefaults(defineProps<{ fileList: any }>(), { fileList: [] })
  const emit = defineEmits(['getUploadData'])
  const fileList = ref<any>([])
  //限制上传类型
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    fileList.value = [...fileList.value, file]
    const iconSize = file.size / 1024 / 1024 < 3
    const isPNG = file.type === 'image/png' || file.type === 'image/jpeg'
    if (!isPNG || !iconSize) {
      fileList.value.splice(fileList.value.indexOf(file), 1)
      message.error(`只能是jpg、png格式且大小不能超过3MB!`)
    }
    if (fileList.value.length > 0) {
      fileList.value = [fileList.value[fileList.value.length - 1]]
    }
    return (isPNG && iconSize) || Upload.LIST_IGNORE
  }
  const customRequest = async (options: any) => {
    const { onSuccess, onError, file, onProgress } = options
    let formData = new FormData()
    formData.append('files', file)
    onProgress({ precent: 80 })
    let res: any = await uploadFile(formData)
    if (res.status === 200) {
      onProgress({ precent: 100 })
      let arr = res?.data?.files
      if (Array.isArray(arr) && arr.length > 0) {
        arr = arr.map((item: any, index: any) => {
          return {
            ...item,
            url:'拼接的路径地址' + item.name,
            uid: index,
          }
        })
      }
      emit('getUploadData', arr)
      onSuccess(res?.data?.files, file)
      message.success('上传成功')
    } else {
      onError(res?.data?.files, file)
      message.error('上传失败')
    }
  }
  watch(
    () => props.fileList,
    (val) => {
      if (val) {
        fileList.value = val
      }
    }
  )
</script>


父组件

 <a-form-item label="上传图片" name="picture">
 	<UploadSingle
      :fileList="fileList"
      @getUploadData="getUploadData"
    ></UploadSingle>
 </a-form-item>
<script lang="ts" setup>
	const fileList = ref<any>([])
  	//获取上传附件后的返回值
  	async function getUploadData(data: any) {
    	formState.value.picture = data
  	}
  	
 // 获取页面数据(回显)
  async function getData() {
    let res: any = await getAnimal({ id: props.propsData.id })
    if (res.code === 20000) {
      let obj = { ...res.data }
      formState.value = obj
      coord.coord = [obj]
      fileList.value = obj.picture //回显
    } else {
      message.error(res.msg)
    }
  }
</script>

在这里插入图片描述

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐