情況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: 指定文件名稱。
