情况1:
有遇到过只需要这样就能成功调用的接口:
const url = process.env.VUE_APP_BASE_API + \'/api/export\' window.location.href = url
情况2:
有时候要麻烦点:
api:
export(params = {}) { return httpPost(\'/api/export\', params, { responseType: \'blob\' }) }
组件:
// 导出数据 exportData() { costModel.export({ page: 1, pageSize: this.total, ...this.searchParams }).then(res => { console.log(\'res\', res) const a = document.createElement(\'a\') // 创键临时url对象 const url = URL.createObjectURL(res) a.href = url a.download = \'表格.xlsx\' a.click() // 释放之前创建的URL对象 window.URL.revokeObjectURL(url) }) },
可以封装一下:
export function exportFile(blob, title, type = \'xlsx\') { const a = document.createElement(\'a\') // 创键临时url对象 const url = URL.createObjectURL(blob) a.href = url // 文件名 a.download = title + \'.\' + type a.click() // 释放之前创建的URL对象 window.URL.revokeObjectURL(url) }
组件中调用:
exportData() { costListModel.export({ page: 1, pageSize: this.total, ...this.searchParams }).then(res => { // console.log(\'res\', res) exportFile(res, \'文件标题\', \'xlsx\') }) },
知识点补充:
URL.createObjectURL()
参考:https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
HTML <a> download 属性
参考:https://www.runoob.com/tags/att-a-download.html
download 属性是HTML5中新增的 <a> 标签属性。
<a download="filename">
filename: 指定文件名称。