我在用 element plus的el-upload组件上传1个图片,el-image组件显示图片的过程中,碰到了图片上传第二次时,无法执行上传替换前一个文件,然后又碰到无法执行 http-request 的问题。具体解决代码如下。
2个组件的定义代码如下:
<el-col :xs="24" :sm="12" :md="12" :lg="24" :xl="24" class="mb20">
<el-form-item label="参考图" prop="image">
<el-upload
ref="myupload"
:show-file-list="true"
:http-request="uploadAttachmentHandle"
:limit="1"
:on-exceed="handleExceed"
:auto-upload="true"
>
<el-button type="primary">上传</el-button>
</el-upload>
<el-image
v-model="imageContainer.imgeurl"
style="width: 100px; height: 100px"
:src="imageContainer.imgeurl"
:zoom-rate="1.2"
:max-scale="7"
:min-scale="0.2"
:preview-src-list="imageContainer.imgeurl"
show-progress
:initial-index="4"
fit="cover"
/>
<!-- :preview-src-list="imgeurl" -->
</el-form-item>
</el-col>
业务函数部分如下:
import { UploadRequestOptions,genFileId } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
//文件上传替换前一个文件
//:limit="1" 属性和 :on-exceed="handleExceed" 配合使用 ,每次替换旧图。 注意limit是1
const myupload = ref<UploadInstance>(); //myupload 必须和 el-upload 组件的ref属性名同名
const handleExceed: UploadProps['onExceed'] = (files) => {
//下面这两行不能在这里执行,执行了就会影响 :http-request="uploadAttachmentHandle" 的接口请
//求执行。要放到下面的函数中最后执行
// if(myupload.value!=undefined)
// myupload.value!.clearFiles();
const file = files[0] as UploadRawFile;
file.uid = genFileId();
myupload.value!.handleStart(file);
}
const uploadAttachmentHandle = async (options: UploadRequestOptions) => {
const res = await cbbjMaterialApi.uploadAttachment(options);
state.ruleForm.image = res.data.result?.id;
imageContainer.imgeurl=res.data.result?.url;
if(myupload.value!=undefined)
myupload.value!.clearFiles();
};
el-upload 插件可以直接通过style样式调整 文件列表宽度