弹框组件(完整代码)
<template>
<div>
<el-dialog title="导入excel" v-if="dialogVisible" :visible.sync="dialogVisible" width="40%">
<el-upload
class="ml-10"
:limit="limitNum"
:auto-upload="false"
accept=".xlsx"
:action="UploadUrl()"
:before-upload="beforeUploadFile"
:on-change="fileChange"
:on-exceed="exceedFile"
:on-success="handleSuccess"
:on-error="handleError"
:file-list="fileList"
>
<el-button slot="trigger" size="small" type="primary">导入资产</el-button>
<!-- <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div> -->
<div class="el-upload__tip" slot="tip">只能上传xlsx文件,且不超过10M</div>
</el-upload>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="uploadFile">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
data() {
return {
limitNum: 1, // 上传excell时,同时允许上传的最大数
fileList: [], // excel文件列表
dialogVisible: false,
};
},
methods: {
UploadUrl() {
// 因为action参数是必填项,我们使用二次确认进行文件上传时,直接填上传文件的url会因为没有参数导致api报404,所以这里将action设置为一个返回为空的方法就行,避免抛错
return "";
},
// 文件超出个数限制时的钩子
exceedFile(files, fileList) {
this.$message.warning(
`只能选择 ${this.limitNum} 个文件,当前共选择了 ${files.length +
fileList.length} 个`
);
},
// 文件状态改变时的钩子
fileChange(file, fileList) {
console.log(file.raw);
this.fileList.push(file.raw);
console.log(this.fileList);
},
// 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传
beforeUploadFile(file) {
console.log("before upload");
console.log(file);
let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
let size = file.size / 1024 / 1024;
if (extension !== "xlsx") {
this.$message.warning("只能上传后缀是.xlsx的文件");
}
if (size > 10) {
this.$message.warning("文件大小不得超过10M");
}
},
// 文件上传成功时的钩子
handleSuccess(res, file, fileList) {
this.$message.success("文件上传成功");
},
// 文件上传失败时的钩子
handleError(err, file, fileList) {
this.$message.error("文件上传失败");
},
uploadFile() {
if (this.fileList.length === 0) {
this.$message.warning("请上传文件");
} else {
let form = new FormData();
form.append("file", this.fileList[0]);
this.$emit('uploadFile',form)
this.fileList = [];
}
}
}
};
</script>
<style scoped>
</style>
封装的请求
import axios from 'axios'
// 导入表格
export const uploadXlsx= (url,data)=>{
return axios({
method: "post",
url: `${url}`,
headers: {
"Content-type": "multipart/form-data"
},
data: data
})
}
main.js引用
import { uploadXlsx } from "./utils/api";
Vue.prototype.uploadXlsx = uploadXlsx;
页面
import imporExcel from './imporExcel';//先引入组件(组件跟页面同级目录)
<el-button type="warning" size="small" @click="imporRuItem">导入资产</el-button>//导入按钮点击出现弹框
// 导入
imporRuItem(){
this.dialogVisible=true
this.$nextTick(() => {
this.$refs["dialogCom"].dialogVisible = true;
});
},
// 发送请求
uploadFile(form) {
this.uploadXlsx('/property/insertProperty',form).then(res=>{
this.dialogVisible=false
this.fetchData()//重新获取自己表格列表的数据
})
},
完整写下来就跟上面一样的效果了