1,统一在接口的请求头里携带token
在src的main.js里写入
//axios配置
axios.interceptors.request.use(
config => {
if (localStorage.getItem('token')) {
config.headers.token = localStorage.getItem('token');
}
//get请求方式中 对数组进行统一处理 格式化数组
// if (config.method === 'get') {
// config.paramsSerializer = function(params) {
// return qs.stringify(params, { arrayFormat: 'repeat' })
// }
// }
return config;
},
error => {
return Promise.reject(error);
});
2,发送请求
// 导出区域能耗数据
async get_daochu_data({commit},v){
let res = await axios.get('xxxxxxxxx接口地址xxxxxxx',{
params:{
dateType: v.dateType,
userId: v.userId,
buildingId: v.buildingId,
parentId:v.parentId,
roomId: v.roomId,
beginTime: v.beginTime,
endTime: v.endTime
},
responseType: 'blob'
})
if(res.status == 200){
commit('SET_DAOCHU_DATA',res.data)
}
}
其中 **responseType: ‘blob’**非常关键,这将让你接收的数据以文件流的方式存储
3,设置按钮(点击按钮即可下载)
页面代码
<div class="table-button">
<el-button type="primary" @click="getDaochu">导出</el-button>
</div>
script代码
getDaochu(){
this.get_daochu_data({
// 区域:
buildingId: this.buildingId,
beginTime: this.month,
parentId: this.pid,
dateType: this.chooseGroupValue,
}).then(()=>{
let url = window.URL.createObjectURL(new Blob([this.daochu_data]));
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", "区域能耗.xls");
document.body.appendChild(link);
link.click();
})
}