Vue3.2+Ts+Element-Plus 文件上传

场景:表单提交,文件上传,点击确认时提交表单数据及文件
请输入图片描述

组件使用

// 上传组件
<el-upload 
  :class="hideUpload ? 'upload_hide' : ''" // 控制上传按钮是否显示
  list-type="picture-card"  // 上传列表样式
  :on-change="fileChange"  // 文件上传或删除触发事件
  :on-preview="handlePictureCardPreview"  // 图片预览
  :on-remove="handleRemove" // 删除图片
  :auto-upload="false"  // 是否自动上传
  :show-file-list="true" // 显示上传列表
  :file-list="fileList" // 绑定文件列表变量
  multiple :limit="8" // 多文件上传,允许上传文件的最大数量
  accept="image/*"> // 上传文件类型
       <el-icon class="avatar-uploader-icon">
               <Plus />
       </el-icon>
</el-upload>

// 图片查看弹窗
<el-dialog v-model="dialogImgVisible" title="图片预览">
       <div style="height:500px;overflow: hidden;">
             <img w-full class="full_img" :src="dialogImageUrl" alt="Preview Image" />
        </div>
</el-dialog>

方法

// 图片列表
const dialogImageUrl = ref(""); // 预览图url
const dialogImgVisible = ref(false); // 预览弹窗
const hideUpload = ref(false); // 是否隐藏上传按钮
const fileList = ref<UploadUserFile[]>([])
// 是否隐藏上传按钮
const updateUploadShown = () => {
    if (fileList.value.length == 8) {
        hideUpload.value = true;
    } else {
        hideUpload.value = false;
    }
}
// 上传文件改变
const fileChange = (file: any, resfileList: any) => {
    fileList.value = resfileList;
    updateUploadShown();
}

// 预览图片
const handlePictureCardPreview = (file: any) => {
    dialogImageUrl.value = file.url;
    dialogImgVisible.value = true;
};

// 删除图片
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
    const list = fileList.value;
    fileList.value.forEach((item, idx) => {
        if (item.uid === file.uid) {
            list.splice(idx, 1);
        }
    })
    fileList.value = list;
    updateUploadShown();
}

// 确认提交
const submit = async () => {
    var formData = new FormData();  // 创建form对象
    fileList.value.forEach((item: any, idx: any) => {
        // 添加文件
        formData.append('files', item?.raw);
    })
    formData.append('form', form); // 表单其它数据
    // 提交接口
    await update(formData).then(res => {
        console.log('res.....',res)
    })
}

样式

.upload_hide :deep .el-upload--picture-card {
    display: none !important;
}
最后修改:2023 年 06 月 19 日
如果觉得我的文章对你有用,请随意赞赏