导入-实际上是上传功能,使用el-upload实现
importFile.vue:
<template>
<div class="import">
<el-upload
ref="upload"
:headers="header"
:action="uploadUrl"
:data="uploadData"
:on-error="handleError"
:on-success="handleSuccess"
:before-upload="beforerUpload"
:show-file-list="false"
>
<el-button size="small" type="primary">导入</el-button>
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
uploadUrl: '', // 请求地址
header: {} // 请求头部
};
},
props: {
uploadData: {
type: Object,
default: () => {} // 上传时附带的额外参数
}
},
methods: {
// 文件上传前的钩子
beforerUpload(file) {
const isXslx =
file.type ===
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isXslx) {
this.$message.error("请上传xslx格式文件");
}
if (!isLt2M) {
this.$message.error("上传文件大小不能超过 2MB!");
}
return isLt2M && isXslx;
},
// 上传失败钩子
handleError(err, file, fileList) {
this.$message.error(err);
},
// 成功上传钩子
handleSuccess(response, file, fileList) {
if (response.success) {
this.$message.success(response.success);
this.$parent.getData(); // 调用父组件方法
} else {
this.$message.error(response.error);
}
}
}
};
</script>
<style lang="scss" scoped>
.import {
display: inline-block;
margin-right: 10px;
}
</style>
调用导入组件
<template>
<div class="import">
<import-file :uploadData="uploadData"></import-file>
</div>
</template>
<script>
export default {
data() {
return {
uploadData: {
}
};
},
mounted() {
this.getData();
},
methods: {
// 获取数据
getData() {
// todo
},
}
};
</script>
导出
exportFile.vue
<template>
<el-button
@click="exportFile"
:url="url"
:fileTitile="fileTitile"
:btnName="btnName"
>{{ btnName}}</el-button>
</template>
<script>
import { toDataStr } from "@/utils/util";
export default {
props: {
url: {
type: String,
default: () => ""
},
fileTitile: {
type: String,
default: () => ""
},
btnName: {
type: String,
default: () => ""
}
},
methods: {
// 导出
exportFile() {
const params = {}; // 上传的参数
let url = toDataStr(params, this.url);
this.$http
.get(url, {
responseType: "arraybuffer"
})
.then(res => {
let aLink = document.createElement("a");
let blob = new Blob([res], {
type:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
aLink.href = URL.createObjectURL(blob);
aLink.setAttribute("download", this.fileTitile + ".xlsx"); // 设置下载文件名称
aLink.click();
});
}
}
};
</script>
将json对象转为key=value形式
// 将json对象转为key=value形式
export const toDataStr = (params, url) => {
let dataStr = ""; //数据拼接字符串
Object.keys(params).forEach(key => {
dataStr += key + "=" + params[key] + "&";
});
if (dataStr !== '') {
dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
url = url + '?' + dataStr;
}
return url;
}
除了excel 还可以根据常见 MIME 类型列表导入导出不同的文件
调用导出组件
<template>
<div class="import">
<export-file url="xxx/xxxx" fileTitile="模板表格" btnName="下载模板">
</export-file>
</div>
</template>
<script>
export default {
data() {
return {
};
},
mounted() {
this.getData();
},
methods: {
// 获取数据
getData() {
// todo
},
}
};
</script>