封装的组件
<div>
<el-dialog :title="title" :visible.sync="dialogVisible" append-to-body width="30%">
<div>
<el-upload
class="upload-demo"
ref="upload"
action="#"
:http-request="httpRequest"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-change="change"
:before-upload="beforeUpload"
:file-list="fileList"
:auto-upload="false"
multiple
>
<div v-if="showScoreImportType" style="width: 100%">
<el-select v-model="scoreImportType" placeholder="请选择活动区域">
<el-option label="只更新不覆盖" value="0"></el-option>
<el-option label="更新+覆盖" value="1"></el-option>
</el-select>
</div>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<div slot="tip" class="el-upload__tip">只能上传XLS/XLSX文件,且不超过2M</div>
</el-upload>
</div>
<span slot="footer" class="dialog-footer">
<el-button @click.stop="cancel">取 消</el-button>
<el-button type="primary" @click.stop="submit">上 传</el-button>
</span>
</el-dialog>
</div>
js
export default {
data() {
return {
dialogVisible: false,
fileList: [],
datas: [],
scoreImportType: "0",
showScoreImportType: false,
myFlag: 0
};
},
props: {
title: {
Type: String,
default: "上传"
}
},
methods: {
show(val) {
this.myFlag = val;
this.dialogVisible = true;
if (val == "showScoreImportType") {
this.showScoreImportType = true;
}
},
beforeUpload(file) {
// const isXls = file.type === "application/vnd.ms-excel";
const isLt2M = file.size / 1024 / 1024 < 2;
// const isXlsx = file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
let suff = file.name.substring(
file.name.lastIndexOf(".") + 1,
file.name.length
);
if (suff != "xls" && suff != "XLS" && suff != "xlsx" && suff != "XLSX") {
this.$message.error("上传文件只能是 XLS/XLSX 格式!");
return;
}
if (!isLt2M) {
this.$message.error("上传文件大小不能超过 2MB!");
return;
}
this.$emit("uploadData", file, this.scoreImportType, this.myFlag);
this.dialogVisible = false;
},
httpRequest(data) {
},
handleRemove(file, fileList) {
},
handlePreview(file) {
},
change(file, fileList) {
},
//取消选择,清空之前的选择
cancel(){
this.dialogVisible = false
this.$refs.upload.clearFiles();
},
submit() {
this.$refs.upload.submit();
this.timer = setTimeout(() => {
this.$parent.updata();
}, 600);
this.$refs.upload.clearFiles();
},
//上传
handleRemove(file, fileList) {
},
handlePreview(file) {
},
handleExceed(files, fileList) {
this.$message.warning(
`当前限制选择 3 个文件,本次选择了 ${
files.length
} 个文件,共选择了 ${files.length + fileList.length} 个文件`
);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`);
}
}
};
父组件调用
<template>
<upload title="导入" ref="upload" @uploadData="uploadData"></upload>
</template>
<script>
uploadData(file){
let formData = new FormData();
formData.append("file", file);
formData.append("fkBaseClassId", this.useId);
importClassStudentApi(formData).then((res)=>{
console.log(res);
})
},
</script>