说明
如题,在用elementUI
的时候,需要用到Upload
上传组件,当list-type
为picture-card
时,即使写了limit
为1,但还是会出现一个新的上传框,如下图:
这时,需要隐藏掉后面的上传框,官方没有给方法,下面记录一下。
正文
首先,说一下思路,一开始准备用v-if= fileList.length > 0
来判断这个upload的显示,结果会导致上传后直接隐藏上传框,元素位移了,v-show
也不行,附上相关代码
模板部分代码:
<el-form-item label="物料图片" prop="photo">
<el-upload
ref="uploadRef"
action="#"
list-type="picture-card"
:class="{ disabled: uploadDisabled }"
:limit="1"
:http-request="requestUpload"
:on-remove="handleRemove"
:before-upload="beforeUpload"
:on-exceed="handleExceed"
:on-preview="handlePictureCardPreview"
:file-list="fileList"
>
<el-icon><Plus /></el-icon>
</el-upload>
<el-dialog v-model="dialogVisible" :visible.sync="dialogVisible">
<img :src="dialogImageUrl" alt="物料图片预览" />
</el-dialog>
</el-form-item>
脚本部分:
const uploadDisabled = ref(false);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const fileList = ref([]);
const beforeUpload = file => {
const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isJPGOrPNG) {
proxy.$message.error('上传图片只能是 JPG 或 PNG 格式!');
}
if (!isLt10M) {
proxy.$message.error('上传图片大小不能超过 10MB!');
}
return isJPGOrPNG && isLt10M;
};
const handleRemove = (file, fileList) => {
uploadDisabled.value = false;
console.log(file, fileList);
};
const requestUpload = options => {
const { file, onSuccess, onError } = options;
const formData = new FormData();
formData.append('file', file);
uploadProductPicture(formData)
.then(response => {
onSuccess(response);
form.value.photo = response.imgUrl;
fileList.value.push({ url: response.imgUrl });
proxy.$message.success('上传成功');
uploadDisabled.value = true;
})
.catch(error => {
onError(error);
proxy.$message.error('上传失败');
});
};
const handleExceed = (files, fileList) => {
proxy.$message.error('只能上传一张图片');
};
const handlePictureCardPreview = file => {
dialogImageUrl.value = file.url;
console.log(dialogImageUrl.value, '预览图片地址');
dialogVisible.value = true;
};
样式部分代码:
:deep(.disabled .el-upload--picture-card) {
display: none !important;
}
注意,在查看或者编辑按钮里,记得加上uploadDisabled.value = true;
,否则还是会显示上传框
效果
放一下图片看看效果,新增时:
上传完成效果:
现在跟文章开头的图片对比,就少了一个上传框,完美解决。