需求是按查詢條件導(dǎo)出

WechatIMG3.png
后端提供的接口是get方式,并且有入?yún)?/p>

WechatIMG1.png
接口返回的是文檔流

WechatIMG2.png
最簡單的方式是利用a標(biāo)簽href直接打開拼接后的get地址。
也可以用window.open()打開拼接好的url,但是后重新打開一個(gè)tab頁,雖然是瞬間的但是體驗(yàn)不好
經(jīng)過谷歌查詢以后采用了以下方式
axios.get(`/insuranceOrder/exportExcel`, { //url: 接口地址
params: this.queryParam,
responseType: `arraybuffer` //一定要寫
})
.then(res => {
if (res.status == 200) {
let blob = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
//word文檔為application/msword,pdf文檔為application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
});
let objectUrl = URL.createObjectURL(blob);
let link = document.createElement("a");
let fname = `保險(xiǎn)詢價(jià)列表`; //下載文件的名字
link.href = objectUrl;
link.setAttribute("download", fname);
document.body.appendChild(link);
link.click();
} else {
this.$message({
type: "error",
message: "導(dǎo)出失敗"
})
}
})