导出

import axios from "axios";
import qs from "qs";
export default function(params) {
return {
data() {
return {
params: {},//get方法时传递的参数
exportData: {},//post方法时传递的参数
token: '',
url: '',//导出接口
excelName: ''//导出文件名
}
},
created() {
this.token = this.$store.state.auth.token;
},
methods: {
getDownload() {
axios({
url: this.url,
params: this.params,
paramsSerializer: param => {
return qs.stringify(param, { indices: false });
},
method: "get",
responseType: "blob",
headers: {
token: this.token
}
})
.then(res => {
const link = document.createElement("a");
const blob = new Blob([res.data], {
type: "application/vnd.ms-excel"
});
link.style.display = "none";
link.href = URL.createObjectURL(blob);
link.setAttribute("download", this.excelName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch(err => {
console.log("debug log --> ", err);
});
},
postDownload() {
axios({
url: this.url,//后端提供的导出接口
data: this.exportData,//传递后端需要的导出参数
method: "post",
responseType: "blob",
headers: {
token: this.token,
"Content-Type": "application/json"
}
})
.then(response => {
const data = response.data;
const url = URL.createObjectURL(data);
const link = document.createElement("a");
link.href = url;
link.download = this.excelName;//自定义导出文件名
link.click();
})
.catch(err => {
console.log("debug log --> ", err);
});
},
}
}
}

posted on 2022-04-14 17:03  阿政kris*  阅读(246)  评论(0编辑  收藏  举报