导入组件的封装
<template><Modal :visible="visible" title="导入" @onSave="onSave" @onCancal="closeDialog"><template #default><el-upload ref="upload" class="upload-demo"action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :limit="1" :on-exceed="handleExceed":auto-upload="false" :on-change="handleChange" :before-upload="beforeUpload" drag:accept="props.accept.join(',')"><el-icon class="el-icon--upload"><upload-filled /></el-icon><div class="el-upload__text">点击或将文件拖拽到这里上传</div><template #tip><div class="el-upload__tip">仅支持{{ props.accept.join(',') }}文件</div></template></el-upload></template></Modal><el-button @click="toggle">导入</el-button>
</template>
<script setup>
import { ref } from "vue";
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus";
import Modal from '@/components/Modal/index.vue'const props = defineProps({requestFn: Function,accept: Array
})const emit = defineEmits(['onSave'])const visible = ref(false)const fileList = ref([])
const upload = ref()// 点击导入
const toggle = () => {// if(upload.value) {// upload.value.submit()// }visible.value = !visible.value
}// 限制
const handleExceed = () => {ElMessage.warning("只能上传一个文件,请先删除");
};// 上传文件
const handleChange = (file) => {if (file.status === "ready") {fileList.value = [file.raw];}
};// 上传文件之前的钩子
const beforeUpload = (file) => {console.log(file)const acceptStr = props.accept.join(',')const fi = props.accept.findIndex(o => file.name.endsWith(o));if (fi === -1) {console.log(`仅支持${acceptStr}格式的文件`)// ElMessage.warn(`仅支持${acceptStr}格式的文件`);} else {// setFileList([file]);}return false;
}// 保存
const onSave = async () => {try {if (fileList.value && fileList.value.length > 0) {const formData = new FormData();fileList.value.forEach(file => {console.log(file)formData.append('file', file)console.log(formData.get('file'))});console.log(formData.get('file'))const res = await props.requestFn(formData)console.log(res)// onClose(true);// setVisible(false);emit('onSave', '')} else {ElMessage.warn('请选择文件');}} catch (e) {console.log(e)}
}// 关闭弹窗
const closeDialog = () => {visible.value = false
}</script>
使用