api中的index.js 接口函数
// 统计分析 唤醒次数统计 导出数据
export function statisticalExport(data){
return request({
url:'/statistical/export',
method:'get',
data,
responseType:"blob"
})
}
views中vue页面
<template>
<el-button type="primary" @click="deriveData">导出数据</el-button>
</template>
export default {
methods:{
// 导出数据方法
async deriveData() {
let res = await statisticalExport();
var ress = window.URL.createObjectURL(res);
var a = document.createElement("a"); //创建一个<a></a>标签
a.href = ress; // 给a标签的href属性值加上地址,注意,这里是绝对路径,不用加 点.
a.style.display = "none"; // 障眼法藏起来a标签
document.body.appendChild(a); // 将a标签追加到文档对象中
a.click(); // 模拟点击了a标签,会触发a标签的href的读取,浏览器就会自动下载了
a.remove(); // 一次性的,用完就删除a标签
},
}
}
如上所示 若 接口函数 statisticalExport 中 使用了 responseType:“blob” 那么 导出方法deriveData中 就不用再 new Blob了;
注意:多数情况下 导出数据,后端返回文件流时 并不会返回 {“code”:200,“mseeage”:“sss”,“data”:{aa:11}}这种格式,后端可能会直接返回二级制文件流。但我们再封装axios时,请求拦截中我们一般会判断res.code:如下所示:
这时候,我们需要再请求拦截中加个判断 首先 res.code要存在
response => {
const res = response.data
// if the custom code is not 20000, it is judged as an error.
if (res.code && res.code !== 200 && res.code !== 20000) {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
小白简单记录总结