1.单独写在一个文件里的导出固定方法
/*** 下载方法* @param response*/
export const downloadFile = (response) => {const res = response.data;const type = res.type;if (type && type.includes("application/json")) {let reader = new FileReader();reader.onload = e => {if (e.target.readyState === 2) {let data = JSON.parse(e.target.result);this.$message({message: data.msg,type: "warning"});}};reader.readAsText(res);} else {let disposition = response.headers["content-disposition"];let fileName = "下载文件.zip";if (disposition) {let respcds = disposition.split(";");for (let i = 0; i < respcds.length; i++) {let header = respcds[i];if (header !== null && header !== "") {let headerValue = header.split("=");if (headerValue !== null && headerValue.length > 0) {if (headerValue[0].trim().toLowerCase() === "filename") {fileName = decodeURI(headerValue[1]);break;}}}}}//处理引号if ((fileName.startsWith("'") || fileName.startsWith('"')) && (fileName.endsWith("'") || fileName.endsWith('"'))) {fileName = fileName.substring(1, fileName.length - 1)}let blob = new Blob([res]);let link = document.createElement("a");link.href = window.URL.createObjectURL(blob);link.download = fileName;link.click();window.URL.revokeObjectURL(link.href);}
}
2.使用方法
引入
<script>
import projectApi from "@/api/project.js";//自己项目的接口文件.
import {downloadFile} from '@/utils/commons' //上文中固定导出方法
methods:{//页面上的导出按钮方法exportExcelasync exportExcel() {let params = {page:this.currentPage,size:this.page,projectNum:this.projectCode,projectName:this.projectName,} //params是参数,//TableExportToExcel是后端自己写的导出方法await projectApi.TableExportToExcel({...params}).then(response => {downloadFile(response);});},}
</script>
非常简单