从Element UI 的官方文档中, Upload 上传组组件提供了on-remove和before-remove的文件删除的钩子属性(回调方法名),但如何调用组件删除方法(让该方法删除本地上传文件列表以及触发这两个钩子)并无相关说明。
在不定义file插槽(slot)的情况下,通过UI点击控件文件列表上文件的叉标签(X),控件的封装内部会为我们触发相应的before-remove钩子、删除组件列表中对应文件信息、on-remove钩子(一般此处调用后台去删除服务端对应文件)等调用,但在我们需要自定义文件列表的模板的情况下,我们需要集成文件删除的操作(包括保持让before-remove钩子、on-remove钩子也像从默认UI的叉标签X删除的情况那样同样生效),而官方文档并没有说明删除操作的API:
官方文档中的例子如下,下载(实现相对简单)、删除操作并无具体举例说明:
没办法,只好分析该组件的源代码:
https://unpkg.com/browse/element-ui@2.15.13/packages/upload/src/index.vue
https://unpkg.com/browse/element-ui@2.15.13/packages/upload/src/upload.vue
https://unpkg.com/browse/element-ui@2.15.13/packages/upload/src/index.vue
根据源码可知,删除操作是通过组件内部的upload子组件(ref为“upload-inner”)调用onRemove回调方法实现的,而该子组件的onRemove回调方法实际引用的是上层组件(el-upload本身)的handleRemove方法;
因此,我们使用el-upload组件可以有以下方法来调用删除文件的操作以触发相应的before-remove钩子、从组件的列表删除对应文件、on-remove钩子:
(假设该el-upload组件ref="upload_attach")
- $refs.upload_attach.$refs['upload-inner'].onRemove(file);
- $refs.upload_attach.handleRemove(file)
<el-upload ref="upload_attach" :file-list="editForm.AttachFileInfos" drag list-type="picture-card" multiple :limit="maxUpload" :on-exceed="handleExceed"
:action="uploadUrl" :auto-upload="autoupload" @*:headers="headers"*@ :data="uploadParam" :on-change="handleChange1"
:on-success="uploadSuccess1" @*:on-preview="previewPic"*@ :on-remove="removeAttachFile1" :before-remove="beforeRemove" :class="{hideUnload:notAttachUploader}">
@*<em class="el-icon-plus"></em>*@
<em class="el-icon-upload"></em>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div slot="file" slot-scope="{file}">
@*<img class="el-upload-list__item-thumbnail" :src="file.url" alt="">*@
<span>{{file.name}}</span>
<span class="el-upload-list__item-actions">
@*<span class="el-upload-list__item-preview"
@click="handlePictureCardPreview(file)">
<i class="el-icon-zoom-in"></i>
</span>*@
<span class="el-upload-list__item-delete"
@@click="handleDownload(file)">
<i class="el-icon-download"></i>
</span>
<span class="el-upload-list__item-delete"
@@click="$refs.upload_attach.$refs['upload-inner'].onRemove(file);"
@*或者:@@click="$refs.upload_attach.handleRemove(file);"*@
>
<i class="el-icon-delete"></i>
</span>
</span>
</div>
</el-upload>
handleDownload: function (file) {
var link = document.createElement("a");
link.setAttribute("href", file.url);
link.setAttribute("download", file.name);
link.setAttribute("target", "_blank");
link.setAttribute("display", "none;");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},
运行效果:文章来源:https://www.toymoban.com/news/detail-684518.html
文章来源地址https://www.toymoban.com/news/detail-684518.html
到了这里,关于el-upload调用内部方法删除文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!