element-plus 之 el-upload上传多图并预览

最近做项目,因为是用vue3+element-plus写的,有上传多图的场景,也是踩了一些坑,在这里总结一下,也分享给有需要的小伙伴。

需要注意的几个点:

  1. :show-file-list=“true” ,一定记得设置成true,我因为没注意设置了false,图片一致回显不出来,纠结了很久;
  2. :auto-upload=“false” ,手动上传,所以需要把这个参数设置为false;
  3. :file-list=“fileList”,fileList就是绑定的文件数据列表;
  4. :limit=“3”,设置最大可上传的文件数,这里需要注意的是,上传按钮并不会到了最大数就不显示,需要自己控制css样式;

预览的时候需要注意:

**<template #file=“{ file }”> **:这里的 #file=“{file}” 是固定写法,不需要换成自己定义的数据,应该和el-table里面scope类似,是内置的,具体为啥,我也没整明白。

具体代码如下:

<template>
  <div class="feedback_wrapper">
    <el-upload
      :class="'upload_wrapper ' + (hideUpload ? 'hide' : '')"
      list-type="picture-card"
      :limit="3"
      :file-list="fileList"
      :show-file-list="true"
      :on-change="fileChange"
      :auto-upload="false"
      accept="image/*"
    >
      <el-icon>
        <Plus />
      </el-icon>
      <template #file="{ file }">
        <div>
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <el-icon>
                <zoom-in />
              </el-icon>
            </span>
            <span class="el-upload-list__item-delete" @click="handleRemove(file)">
              <el-icon>
                <Delete />
              </el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img w-full class="full_img" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { Delete, Plus, ZoomIn } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
const fileList = ref([]); // 图片列表
const dialogImageUrl = ref(""); // 预览图url
const dialogVisible = ref(false); // 预览弹窗
const hideUpload = ref(false); // 是否隐藏上传按钮
// 更新上传加号按钮显示状态
function updateUploadShown() {
  if (fileList.value.length == 3) {
    hideUpload.value = true;
  } else {
    hideUpload.value = false;
  }
}
// 文件改变
function fileChange(file, resfileList) {
  fileList.value = resfileList;
  updateUploadShown();
}
// 移除图片
const handleRemove = (file) => {
  const list = fileList.value;
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1);
    }
  }
  fileList.value = list;
  updateUploadShown();
};
// 预览图片
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};
</script>

最后还有一个坑想说:

on-change事件: 事件参数(UploadFile,UploadFiles),UploadFiles参数,如果用JSON.parase(JSON.stringif(UploadFiles)),部分数据会丢失,最重要的是,改变了file.raw的类型,所以如果用此方法转换了,上传的时候, 因为类型不对,会报错。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐