vue3+elementplus创建一个多图片上传表单

40 阅读1分钟

image.png

<template>
  <el-form ref="ticketFormRef" label-width="120px" class="ticketForm" status-icon>
    <el-form-item>
      <el-upload
        v-model:file-list="fileList"
        :auto-upload="false"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>

      <div slot="footer" style="display: flex; justify-content: flex-end; padding-right: 22px;">
        <el-button type="primary" @click="submitForm">上传</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-form-item>
  </el-form>

  <div>{{ fileList }}</div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { Plus } from '@element-plus/icons-vue';

const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const oldFileList = ref([]);



const handleRemove = (file, fileList) => {
  console.log(file, fileList, fileList.value);
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

const submitForm = () => {
  // 在这里添加表单提交的逻辑
  console.log('表单提交');
};

const cancel = () => {
  fileList.value = [];
};

watch(fileList, (newFileList) => {

  console.log('File list changed:', newFileList);
  const ofl = oldFileList.value.length;
  const nfl = newFileList.length;
  if (ofl >= 1 && nfl >= 2 && nfl - ofl === 1) {
    // 验证图片重复
    const addedFile = newFileList[nfl - 1];
    const isDuplicate = oldFileList.value.some((item) => (item.name === addedFile.name) && (item.size === addedFile.size));
    if (isDuplicate) {
      fileList.value = oldFileList.value;
    }

    // 验证文件类型
    const allowedTypes = ['image/jpeg', 'image/png'];
    if (!allowedTypes.includes(newFileList[0].raw.type)) {
        fileList.value = oldFileList.value;
    }

    // 验证文件大小
    const maxSize = 2 * 1024 * 1024; // 2MB
    if (newFileList[0].size > maxSize) {
      fileList.value = oldFileList.value;
    }
    
  } else if(ofl == 0 && nfl == 1 ) {
    // 验证文件类型
    const allowedTypes = ['image/jpeg', 'image/png'];
    if (!allowedTypes.includes(newFileList[0].raw.type)) {
        fileList.value = oldFileList.value;
    }

    // 验证文件大小
    const maxSize = 2 * 1024 * 1024; // 2MB
    if (newFileList[0].size > maxSize) {
      fileList.value = oldFileList.value;
    }

  }
  oldFileList.value = [...newFileList];
});
</script>