element-plus 文件上传基础封装
对项目中用到的上传组件,做一个简单的封装
<template>
<el-upload
ref="uploadRef"
:action="action"
:list-type="listType"
:limit="limit"
:accept="accept"
:on-remove="handleRemove"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:on-exceed="handleExceed"
>
<el-button type="primary">上传</el-button>
</el-upload>
</template>
<script setup>
/**
* 文件上传
*/
import { ElNotification } from '@jlz/element-plus';
import { ref } from 'vue';
const props = defineProps({
action: {
type: String,
default: '/file/local/upload',
},
listType: {
type: String,
default: 'picture-card',
},
// 默认为0上传数量无限制
limit: {
type: Number,
default: 0,
},
accept: {
type: String,
default: '',
},
});
const emit = defineEmits(['uploadedList']);
const uploadRef = ref();
function handleExceed() {
ElNotification({
title: '操作有误',
message: `已超出限制,上传最多数量为${props.limit}`,
type: 'warning',
});
}
function handleSuccess(_, uploadFile, uploadFiles) {
const resArr = uploadFiles.map((item) => item.response.data);
emit('uploadedList', resArr);
}
// 删除前的回调
function handleRemove(uploadFile, uploadFiles) {
const resArr = uploadFiles.map((item) => item.response.data);
emit('uploadedList', resArr);
}
// 上传之前,可在此做文件限制
function beforeUpload() {
// console.log(file);
}
</script>
<style lang="scss" scoped>
// aa
</style>
页面使用
<Uploader
:list-type="'text'"
:accept="'.pdf'"
:limit="1"
@uploaded-list="uploadedList"
/>