vue3 + element Plus el-load上传组件封装

959 阅读1分钟
//父组件 结构
<el-dialog v-model="UploadingVisible" width="60%" title="上传产权规划图">
    <uploadingPic @uploadChange="uploadChange" :index="picIndex" :category="category" :modelValue="fileList" :uploadFileList="uploadList" />
</el-dialog>
~~~~
<el-form-item label="产权规划图" label-width="140px" prop="originalFileName">
	<el-input v-model="itemProject.originalFileName" disabled placeholder="请上传产权规划图" style="width: 200px; margin-right: 5px" /> 
        <el-button type="primary" @click="openUploading(index, 'project')">点击上传</el-button>
</el-form-item>

~~~~
// 上传规划图dialog
function openUploading(index: any, module: string) {
	// console.log("🚀 ~ file: index.vue ~ line 2500 ~ openUploading ~ index", index)
	UploadingVisible.value = true
	picIndex.value = index
	category.value = module
	if (module === 'property') {
		fileList.value = propertyList[index].fileUploadInfoList
		uploadList.value = propertyList[index].fileUploadInfoList
	} else {
		fileList.value = projectList[index].fileUploadInfoList
		uploadList.value = projectList[index].fileUploadInfoList
	}

	// console.log(propertyList[index].fileUploadInfoList,'111111111111111111111');

}
//子组件触发的方法
function uploadChange(value: any, index: number, category: string) {
	console.log("🚀 ~ file: index.vue ~ line 2460 ~ uploadChange ~ category", category)
	// console.log(value, 'value---------')
	var categoryData;
	UploadingVisible.value = false
	if (category == 'property') {
		categoryData = propertyList[index]
	} else {
		categoryData = projectList[index]
	}
	categoryData.originalFileName = []
	categoryData.fileUploadInfoList = value
	console.log('value', value)
	for (let i = 0; i < value.length; i++) {
		categoryData.originalFileName.push(value[i].originalFileName)
	}
  }
//子组件
<template>
  <div class="component-upload-image">
    <el-upload :multiple="true" :action="uploadImgUrl" list-type="picture-card"
      :before-upload="handleBeforeUpload" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed"
      name="files" :on-remove="handleRemove" :show-file-list="true" :headers="headers" :file-list="fileList" :auto-upload="false"
      :on-preview="handlePictureCardPreview" :class="{ hide: fileList.length >= limit }">
      <el-button type="primary" style="margin: auto">点击上传</el-button>
      <!-- <el-icon class="avatar-uploader-icon"><plus /></el-icon> -->
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
      </template>
      的文件
    </div>

    <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
      <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
    </el-dialog>
    <div class="dialog-footer">
      <el-button class="footerBtn" type="primary" @click="handleUploadSuccess">确认</el-button>
    </div>
    
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";

import {
	uploadPic
} from '../../../../api/system/enterpriseAdd'
import { onMounted } from "vue";

const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: {
    type: Number,
    default: 10,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 100,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["png", "jpg", "jpeg"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: false,
  },
  index: {
    type: Number,
    default: 0,
  },
  category: {
    type: String,
    default: "",
  },
  uploadFileList: {
    type: Array,
    default: [],
  }
});
const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const fileSize = ref(0);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(
  import.meta.env.VITE_APP_BASE_API + "/common/cos/uploads"
); // 上传的图片服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
const fileList = ref([]);

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : props.modelValue.split(",");
      // 然后将数组转为对象数组
      fileList.value = list.map((item) => {
        // if (typeof item === "string") {
        //   if (item.indexOf(baseUrl) === -1) {
        //     item = { name: baseUrl + item, url: baseUrl + item };
        //   } else {
        //     item = { name: item, url: item };
        //   }
        // }
        return item;
      });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);

// 删除图片
function handleRemove(file, files) {
  console.log('fileList.value', fileList.value)
  if (fileList.value.length === 0) {
    props.uploadFileList.splice(0)
  }
  fileList.value.forEach(data => {
    var index = -1
    props.uploadFileList.forEach((uploadFile, i) => {
      if (data.fileName && data.fileName !== uploadFile.fileName) {
        index = i;
      }
    })
    if (index >= 0) {
        console.log('index', index)
      props.uploadFileList.splice(index, 1)
    }
  })
  // emit("update:modelValue", listToString(fileList.value));
}

// 上传成功回调
async function handleUploadSuccess() {
  // console.log(props.category, 'props.category')
  // console.log(res.data[0], "res");
  // uploadList.value.push({ name: res.data.originalFileName, url: res.data.url })
  
  var formData = new FormData();
  var isFile = false
  console.log('fileList', fileList.value)
  fileList.value.forEach(file => {
    if(file.raw) {
      isFile = true
      formData.append('files', file.raw)
    }
  });
  if (isFile) {
    console.log('isFile', isFile)
  const res = await uploadPic(formData)
  if (res.code == 200) {
    res.data.map(file => {
      props.uploadFileList.push(file)
  })
  } else {
    proxy.$modal.msgError('上传失败!')
  }
  }
  
  // console.log("🚀 ~ file: uploadingPic.vue ~ line 133 ~ handleUploadSuccess ~ res", res)
  
  

  number.value = 0;
  // if (props.category == '1') {
  console.log('props.uploadFileList', props.uploadFileList)
  emit("uploadChange", props.uploadFileList, props.index, props.category);


  // proxy.$modal.closeLoading();
  // }
}

// 上传前loading加载
function handleBeforeUpload(file) {
  fileSize.value += file.size
  let isImg = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isImg = props.fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } else {
    isImg = file.type.indexOf("image") > -1;
  }
  if (!isImg) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = fileSize.value / 1024 / 1024 < props.fileSize;
    
    if (!isLt) {
      proxy.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传图片,请稍候...");
  number.value++;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError() {
  proxy.$modal.msgError("上传图片失败");
  proxy.$modal.closeLoading();
}

// 预览
function handlePictureCardPreview(file) {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (undefined !== list[i].url && list[i].url.indexOf("blob:") !== 0) {
      strs += list[i].url.replace(baseUrl, "") + separator;
    }
  }
  return strs != "" ? strs.substr(0, strs.length - 1) : "";
}
// onMounted(() => {
//   if (props.fileInfo) {
//     fileList.value = props.fileInfo
//   } else {
//     fileList.value=[]
//   }
//   //  fileList.value = props.fileInfo
//   console.log("🚀 ~ file: uploadingPic.vue ~ line 203 ~ onMounted ~ props.fileInfo", props.fileInfo)
// })
</script>
<style scoped>
.footerBtn{
  margin: auto 0 auto 90%;
  /* margin-right: 10px; */
}
</style>