vue3 ant-vue form表单里的upload组件封装

<template>
  <a-upload
    v-model:file-list="fileList"
    name="file"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    :action="action"
    :before-upload="beforeUpload"
    @change="handleChange"
    v-bind="$attrs"
  >
    <a-image
      :width="48"
      :height="48"
      v-if="value" :src="value"
    />
    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
    </div>
  </a-upload>
</template>
<script>
import { defineComponent, ref, watch } from 'vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

export default defineComponent({
  components: {
    LoadingOutlined,
    PlusOutlined,
  },
  props:['value'],
  inheritAttrs: false,
  emits:['update:value'],
  setup(props,{emit}) {
    const fileList = ref([]);
    const loading = ref(false);
    const imageUrl = ref();
    const action = ref(`http://192.168.2.2:8080/uplaodurl`);
    const handleChange = info => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        return;
      }

      if (info.file.status === 'done') {
          loading.value = false;
        if(info.file.response.code==0){
          emit('change',info)
          imageUrl.value = info.file.response.data;
        }
      }

      if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
      }
    };

    const beforeUpload = file => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

      if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
      }

      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
      }

      return isJpgOrPng && isLt2M;
    };
    watch(imageUrl, (newValue, oldValue) => {
      emit('update:value', newValue)
    });
    return {
      fileList,
      loading,
      imageUrl,
      action,
      handleChange,
      beforeUpload,
    };
  },
});
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 64px;
  height: 64px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值