import axios from "axios"
import { getToken } from "@/utils/auth"
/** 导出 */
export function exportData(url, query, filename) {
axios({
method: "get",
url: process.env.VUE_APP_BASE_API + url,
responseType: "blob",
params: query || {},
headers: {
Authorization: getToken(),
},
}).then(res => {
// console.log(res);
// 创建一个下载链接
const downloadLink = document.createElement("a");
downloadLink.href = URL.createObjectURL(res.data);
if (filename) {
downloadLink.download = filename
} else {
// 设置下载的文件名为后台返回的文件名
const contentDisposition = res.headers["content-disposition"];
const filenameMatch = contentDisposition.match(/filename=(.+)$/);
const file = filenameMatch ? filenameMatch[1] : "download.xlsx";
downloadLink.download = decodeURIComponent(file);
}
// 触发下载
downloadLink.click();
// 清除创建的下载链接
URL.revokeObjectURL(downloadLink.href);
}).catch((error) => {
console.error("下载 Excel 文件出错:", error);
})
}
先创建一个utils.js文件,封装一段js导出代码;
import { exportData } from "../utils";
/** 导出 */
exportData() {
// @TODO
const filename = `差错明细${formatNow("YYYY-MM-DD")}.xlsx`;
const query = {...this.payload}
delete query.pageNum
delete query.pageSize
exportData(
"/api/settlement/api/reconciliation/record/daily/export",
query,
filename
);
},
再向所用组件引用此方法即可,query代表需要单独传递的参数;