Vue3 Element Plus上传文件封装
时间: 2023-08-10 14:02:46 浏览: 73
以下是一个简单的 Vue3 Element Plus 文件上传组件封装:
```vue
<template>
<el-upload
:class="uploadClass"
:action="uploadUrl"
:headers="uploadHeaders"
:data="uploadData"
:multiple="multiple"
:limit="limit"
:file-list="fileList"
:auto-upload="autoUpload"
:show-file-list="showFileList"
:on-change="handleChange"
:before-upload="beforeUpload"
:on-exceed="handleExceed"
:on-success="handleSuccess"
:on-error="handleError"
>
<el-button :size="buttonSize" type="primary">{{ buttonText }}</el-button>
<div slot="tip" class="el-upload__tip">{{ uploadTip }}</div>
</el-upload>
</template>
<script>
import { ref } from 'vue';
export default {
props: {
uploadUrl: {
type: String,
required: true
},
uploadHeaders: Object,
uploadData: Object,
uploadClass: String,
multiple: {
type: Boolean,
default: false
},
limit: {
type: Number,
default: 3
},
fileList: {
type: Array,
default: () => []
},
autoUpload: {
type: Boolean,
default: true
},
showFileList: {
type: Boolean,
default: true
},
buttonSize: {
type: String,
default: 'medium'
},
buttonText: {
type: String,
default: '点击上传'
},
uploadTip: {
type: String,
default: '只能上传jpg/png文件,且不超过2MB'
}
},
setup(props, { emit }) {
const uploadRef = ref(null);
function handleChange(file, fileList) {
emit('change', file, fileList);
}
function beforeUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
function handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 ${props.limit} 个文件,本次选择了 ${files.length} 个文件,共选择了 ${fileList.length} 个文件`);
}
function handleSuccess(response, file, fileList) {
emit('success', response, file, fileList);
}
function handleError(error, file, fileList) {
emit('error', error, file, fileList);
}
// 返回需要暴露给父组件的数据和方法
return {
uploadRef,
handleChange,
beforeUpload,
handleExceed,
handleSuccess,
handleError
};
}
};
</script>
```
这个组件的主要功能是将 Element Plus 的 Upload 组件进行封装并暴露出一些常用的事件和方法,方便在父组件中进行调用。其中,`uploadUrl` 是必传的属性,用于指定上传接口的地址。其他属性都有默认值,并可以通过传递 props 进行修改。