前端VUE頁面上的匯出或者下載功能,一般是呼叫后端的一個介面,由介面生成excel,word這些檔案的流資訊,回傳給vue,然后由vue去構建下載的動作,這邊整理了一下,封裝了一下,方便以后復用,
封裝一個download檔案
使用年月日時分秒毫秒做為檔案的名稱,下載為excel檔案
/**
* 下載檔案
*/
export const downloadFile = (url,ext, params) => {
let accessToken = getStore('accessToken');
return axios({
method: 'get',
url: `${base}${url}`,
params: params,
headers: {
'accessToken': accessToken
},
responseType: 'blob', //二進制流
}).then(res => {
// 處理回傳的檔案流
const content = res;
const blob = new Blob([content], { type: 'application/vnd.ms-excel;charset=utf-8' });
var date =
new Date().getFullYear() +
"" +
(new Date().getMonth() + 1) +
"" +
new Date().getDate() +
"" +
new Date().getHours() +
"" +
new Date().getMinutes() +
"" +
new Date().getSeconds() +
"" +
new Date().getMilliseconds();
const fileName = date + "." + ext;
if ("download" in document.createElement("a")) {
// 非IE下載
const elink = document.createElement("a");
elink.download = fileName;
elink.style.display = "none";
elink.href = https://www.cnblogs.com/lori/p/URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 釋放URL 物件
document.body.removeChild(elink);
} else {
// IE10+下載
navigator.msSaveBlob(blob, fileName);
}
});
};
為具體功能封裝一個組件,方便在前臺呼叫
// 評價匯出
export const getRecordExport= (params) => {
return downloadFile('/record/export',"xlsx", params)
}
vue頁面上呼叫它,實作匯出
<script>
import {
getReportExport
} from "@/api/index";
import util from "@/libs/util.js";
export default {
name: "task-manage",
data() {},
methods: {
exportExcel() {
getReportExport(this.searchForm).then(res=>{});
}
}
}
截圖

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/36886.html
標籤:JavaScript
上一篇:d3js scales深入理解
下一篇:面試題:整理
