1、 首先要设置get或者post请求的类型。这里我用到post请求
eg:在http.ts中添加公共的方法。
export function post1(url: string, params: any): Promise<AxiosResponse> | Promise<AxiosResponse<any>> {return new Promise((resolve, reject) => {server.post(url, params, { responseType: "blob" }).then((res) => {if (res.data.code == 401) {setTimeout(() => {// window.location.href = "/";// location.reload()setLocalStorage("access_token", null);// location.reload()}, 500);} else if (res.data.code == 499 || res.data.code == 401) {} else if (res.data.code == 403 || res.data.code == 402) {ElMessage.error("登录已过期,请重新登录");setTimeout(() => {setLocalStorage("access_token", null);}, 500);}resolve(res.data);}).catch((err) => {reject(err);});});
}
2、在api.ts中引用
export const export = (params?: any) => post1("/xx/xx/xx", params);
3、页面下载
<el-button @click="exportExcel" :icon="Download" size="small" :disabled="exportExcelDisabled">导出报表</el-button>
const exportExcelDisabled = ref(false);
async function exportExcel() {exportExcelDisabled.value = true; // 防止双击let params = { ...form };await exportWalletTransaction(params).then((res: any) => {const blob = new Blob([res], {type: "application/vnd.ms-excel;charset=UTF-8"});const url = window.URL.createObjectURL(blob); // 创建URL对象const link = document.createElement("a"); // 创建a标签link.href = url;link.download = "xx" + moment(new Date().getTime()).format("YYYY-MM-DD HH-mm-ss") +".xlsx"; // 设置下载文件名,可以用moment插件添加具体时间document.body.appendChild(link);link.click();document.body.removeChild(link);window.URL.revokeObjectURL(url);exportExcelDisabled.value = false; // 防止双击});
}