新建一个封装方法的 exportUtils.js 文件
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.axios = axios;
// 导出
export default {
exportMethod: function(data) {
axios({
method: data.method,
url: data.url,
data: data.data,
responseType: 'blob',
headers: {
'Content-Type': 'application/json'
}
}).then((res) => {
const link = document.createElement('a')
let blob = new Blob([res.data], {
type: 'application/vnd.ms-excel'
// type: "application/pdf;charset=utf-8", //.pdf
})
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
link.download = data.fileName + '.xls' //下载的文件名 注意:加.xls是兼容火狐浏览器
document.body.appendChild(link)
link.click() //会触发a标签的href
// document.body.removeChild(link)
link.remove(); // 一次性的,用完就删除a标签
}).catch(error => {
console.log(error)
})
}
}
引用 js 文件:
// 全局引用在 man.js
import exportUtils from "./utils/exportUtils"
Vue.prototype.exportUtils = exportUtils ;
//局部引入,谁用谁引
import exportUtils from "../../utils/exportUtils.js"
调用方法:
1、全局引用
// 导出
exportOut () {
let params = { list: this.formInline };
let myObj = {
method: 'post',
url: "/dutyTask/dutyTaskExcel", //接口地址
fileName: '值守任务',
data: params,
}
//调用封装方法
this.exportUtils.exportMethod(myObj);
},
2、局部引用
//局部引入,谁用谁引
import exportUtils from "../../utils/exportUtils.js"
// 导出
exportOut () {
let params = { list: this.formInline };
let myObj = {
method: 'post',
url: "/dutyTask/dutyTaskExcel", //接口地址
fileName: '值守任务',
data: params,
}
//调用封装方法
exportUtils.exportMethod(myObj);
},
pdf., xlsx (不封装,直接用)
async downloadFile(row) {
let url =https://blog.csdn.net/"; // 后端接口
let params = { id: row.id }; // 传值 参数
try {
let res = await this.$axios.post(url, params, { responseType: "blob" });
let link = document.createElement("a");
link.style.display = "none";
let blob = new Blob([res], {
type: "application/pdf;charset=utf-8",
// type: 'application/vnd.ms-excel' // Excel .xls
});
link.href = URL.createObjectURL(blob);
link.download = `${row.prjName}备案表.pdf`;
// 获取文件名
document.body.appendChild(link);
link.click(); //会触发a标签的href
link.remove(); // 一次性的,用完就删除a标签
} catch (error) {}
},