util.js里面通用方法
/* 通用导出方法 接收二进制文件生成链接下载 suffixType 文件尾缀类型 这里举例了一些常用的 更多类型访问 https://blog.csdn.net/m0_64210833/article/details/130202081*/export function educe(url, params={}, filename="", suffixType='xlsx') { let suffixTypes = [ {type:'xls', blobType:'application/vnd.ms-excel'}, {type:'xlsx', blobType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}, {type:'doc', blobType:'application/msword'}, {type:'docx', blobType:'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}, {type:'pdf', blobType:'application/pdf'}, {type:'ppt', blobType:'application/vnd.ms-powerpoint'}, {type:'pptx', blobType:'application/vnd.openxmlformats-officedocument.presentationml.presentation'}, {type:'png', blobType:'image/png'}, {type:'jpeg', blobType:'image/jpeg'}, {type:'jpg', blobType:'image/jpeg'}, {type:'gif', blobType:'image/gif'}, {type:'mp3', blobType:'audio/mpeg'}, ]; let n_b_t = suffixTypes.find( i => i.type===suffixType).blobType; return service({ url, method: "GET", params, responseType: "arraybuffer", }).then(async (res) => { // 用返回二进制数据创建一个Blob实例 let blob = new Blob([res], {type:n_b_t}); // 通过URL.createObjectURL生成文件路径 let url = window.URL.createObjectURL(blob); // 创建a标签 let ele = document.createElement("a"); ele.style.display = 'none'; // 设置href属性为文件路径,download属性可以设置文件名称 ele.href = url; ele.download = filename; // 将a标签添加到页面并模拟点击 document.querySelectorAll("body")[0].appendChild(ele); ele.click(); // 移除a标签 ele.remove(); }).catch(error => { this.$message({ showClose: true, message: error.errmsg, type: 'error'}); })}
使用形式
this.$educe( "/newsalary/api/data-list/export", //api地址 this.formData, //参数 "数据采集表详情" ,//下载名称 );