vue3+elementUI中upload,限制图片只能上传一个
·
页面部分
<ElFormItem label="广告图" :limit="1" prop="cover" required>
<ElUpload
v-model:file-list="imgurl"
:class="{ disabled: uploadDisabled }"
:limit="1"
:auto-upload="false"
action="#"
accept="image/jpeg,image/jpg,image/png"
list-type="picture-card"
:on-change="handleFileChange"
:on-remove="handleRemove"
>
<ElButton>选择图片</ElButton>
<template #tip>
<div class="el-upload__tip">只能上传jpg/png图片</div>
</template>
</ElUpload>
</ElFormItem>
js部分
const uploadDisabled = ref(false);
/**修改图片 */
const handleFileChange = (file: any, files: any) => {
if (files.length >= 1) {
uploadDisabled.value = true;
} else {
uploadDisabled.value = false;
}
imgurl.value = files;
modalformData.value.cover = file;
};
function handleRemove(file: any, files: any) {
uploadDisabled.value = false;
}
//新增或者编辑上传的图片调出的弹窗框
const [Modal, modalApi] = useVbenModal({
onOpenChange(isOpen: boolean) {
if (isOpen) {
data.value = modalApi.getData<Record<string, any>>();
title.value = data.value.title;
modalformData.value = data.value.formData;
//编辑数据图片回显
if (modalformData.value.cover) {
imgurl.value = [{ url: data.value.formData.coverUrl }];
//编辑的时候判断只显示一个上传图片
if (data.value.formData.coverUrl) {
uploadDisabled.value = true;
} else {
uploadDisabled.value = false;
}
}
}
},
async onClosed() {
imgurl.value = [];
},
async onConfirm() {
await formRef.value.validate();
if (!imgurl.value.length) {
ElMessage.error("请上传广告图");
return;
}
/**只有修改了图片才需要从oss获取图片地址 */
const file = imgurl.value[0].raw as File;
if (file) {
const coverUrl = await uploadToOSS(file);
modalformData.value.cover = coverUrl; // 保存 OSS 路径
}
if (modalformData.value.id === 0) {
await addSupesrSystemAdApi({ ...modalformData.value });
ElMessage.success("添加成功");
} else {
await upSupesrSystemAdApi({ ...modalformData.value });
ElMessage.success("修改成功");
}
const data = modalApi.getData<{ onRefresh?: Function }>();
data.onRefresh?.();
modalApi.setState({ loading: false });
modalApi.close();
imgurl.value = [];
},
});
css部分
<style lang="scss" scoped>
:deep(.disabled) .el-upload.el-upload--picture-card {
display: none !important;
}
:deep(.disabled) .el-button--success.is-plain {
display: none !important;
}
</style>
更多推荐

所有评论(0)