为了对 Element UI 的 <el-upload> 组件进行二次封装,并且使其能够接受原组件的所有参数,同时添加文件大小限制的功能,你可以创建一个新的 Vue 组件,该组件接收必要的 props 并传递给内嵌的 <el-upload> 组件。
下面是一个示例代码,展示了如何创建这样一个二次封装的上传组件:
<template>
<el-upload
:class="['custom-upload', className]"
:action="action"
:before-upload="beforeFileUpload"
:on-success="handleSuccess"
:on-error="handleError"
:auto-upload="autoUpload"
:list-type="listType"
:file-list="fileList"
:multiple="multiple"
:drag="drag"
:limit="limit"
:on-exceed="handleExceed"
:accept="accept"
:disabled="disabled"
:show-file-list="showFileList"
:with-credentials="withCredentials"
:http-request="httpRequest"
v-bind="$attrs"
v-on="$listeners"
>
<slot></slot>
</el-upload>
</template>
<script>
export default {
name: 'CustomUpload',
props: {
// 继承所有 el-upload 的 props
// 这里仅列出部分作为示例,你可以根据需要添加更多
action: {
type: String,
required: true
},
autoUpload: {
type: Boolean,
default: true
},
fileList: {
type: Array,
default: () => []
},
multiple: {
type: Boolean,
default: false
},
drag: {
type: Boolean,
default: false
},
limit: {
type: Number,
default: 0
},
accept: {
type: String,
default: ''
},
// ... 其他 el-upload 的 props
// 自定义 props(可选)
className: {
type: String,
default: ''
},
maxSize: {
type: Number,
default: 50 * 1024 * 1024 // 50MB
}
// ... 你可以添加其他自定义 props
},
methods: {
beforeFileUpload(file) {
const isLtMaxSize = file.size / 1024 / 1024 < this.maxSize / 1024 / 1024; // 转换为MB进行比较
if (!isLtMaxSize) {
this.$message.error('上传文件大小不能超过 50MB!');
return false;
}
// 可以在这里添加其他文件验证逻辑
return true;
},
handleSuccess(response, file, fileList) {
// 处理上传成功逻辑
this.$emit('success', response, file, fileList);
},
handleError(err, file, fileList) {
// 处理上传失败逻辑
this.$emit('error', err, file, fileList);
},
handleExceed(files, fileList) {
// 处理文件超出限制逻辑
this.$message.warning('文件数量超出限制!');
},
// ... 其他方法
}
};
</script>
<style scoped>
/* 自定义样式 */
.custom-upload {
/* ... */
}
</style>
在这个示例中,CustomUpload 组件接收 el-upload 组件的所有 props,并且添加了一个自定义的 maxSize prop 来设置文件大小限制。beforeFileUpload 方法用于在文件上传之前检查文件大小,如果文件大小超过限制,则显示错误消息并阻止文件上传。
通过 v-bind="$attrs" 和 v-on="$listeners",你可以将父组件传递给 CustomUpload 组件的其他属性和事件监听器传递给内嵌的 <el-upload> 组件。这样,你就可以像使用原生的 <el-upload> 组件一样使用 CustomUpload 组件,并且享受额外的文件大小限制功能。