一 新打开一个页面导出
window.open(
"https://。。。/collCusAide/page/export?authorization=ba10a639-bd05-47b2-90d9-7b2b75633925",
"_blank"
)
二、当前页面导出
common.ts中声明导出方法
import axios from "axios"
import dayjs from "dayjs"
/**
* 通用文件下载方法
* @param {string} url - 请求地址
* @param {Object} params - 请求参数
* @param {string} method - 请求方法 (默认: POST)
*/
export async function downloadFile({
url,
params = {},
method = "POST",
headers = {},
name = "集客助手明细" + dayjs().format("YYYYMMDD")
}) {
try {
// 发起请求,设置 responseType 为 'blob'
const response = await axios({
url,
method,
data: method === "POST" ? params : undefined, // 仅 POST 时传递请求体
params: method === "GET" ? params : undefined, // 仅 GET 时传递查询参数
responseType: "blob",
headers: {
...headers, // 合并传入的 headers
authorization: localStorage.getItem("accessToken") // 添加 auth 参数
}
})
// 创建 Blob 对象
const blob = new Blob([response.data], {
type: response.headers["content-type"] || "application/octet-stream"
})
// 从响应头中获取文件名
const disposition = response.headers["content-disposition"]
console.log(disposition, "disposition")
const filename = disposition
? decodeURIComponent(disposition.split("filename=")[1]?.replace(/['"]/g, ""))
: name + ".xlsx" // 默认文件名
// 创建下载链接并触发下载
const urlObject = window.URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = urlObject
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
// 释放 Blob URL
window.URL.revokeObjectURL(urlObject)
} catch (error) {
console.error("文件下载失败:", error)
throw error // 抛出错误,便于外部处理
}
}
2 使用
<el-button :loading="isLoading" class="importButton" @click="exportPage">导出</el-button>
import { downloadFile } from "@/utils/common"
/** 导出 */
const isLoading = ref<any>(false)
const exportPage = async () => {
isLoading.value = true
try {
let params: any = toRaw(queryForm.value)
delete params.pageIndex
delete params.pageSize
if (contactIds.value?.length > 0) {
params.contactIds = contactIds.value
}
const baseUrl = /^https?:\/\/pre-/g.test(window.origin)
? "https://pre-。。。。/crm-web"
: import.meta.env.VITE_API_BASE_PATH
await downloadFile({
url: baseUrl + "/collCusAide/page/export",
params: params,
method: "POST",
headers: {}
})
// 更新列表
delete queryForm.value.contactIds
getJiKeList()
jeKeTable.value?.clearSelection()
} catch (err) {
} finally {
isLoading.value = false
}
}
注意: 导出方法不加await , el-button的loading图案不会出来 : 因为异步并没有等着接口执行就已经走完了。