原理就是通過a標籤的href屬性將二進制表格數據轉化爲表格,再通過download屬性將文件下載到本地;
需要注意的是接口請求的數據類型要設置爲 blob 類型 具體參考 axios https://www.npmjs.com/package/axios
responseType: 'blob'
具體的代碼
let url = window.URL.createObjectURL(res.data);
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', filename); // filename 自定義下載的表格名稱及後綴名;
document.documentElement.appendChild(link);
link.click();
document.documentElement.removeChild(link);
完整的例子:
// 首先要引入axios
import axios from 'axios';
// 組件內部新增方法
downloadExl(filename) {
axios({
method: 'get',
url: '/api/export',
params: Object, // Object 導出接口所需要的參數對象
responseType: 'blob'
}).then(res => {
let url = window.URL.createObjectURL(res.data);
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', filename);
document.documentElement.appendChild(link);
link.click();
document.documentElement.removeChild(link);
}).catch(e => {
console.log('導出失敗')
}).finally(() => {
console.log('不管導出成功/失敗')
});
},