封装到工具类 utils 目录下
import axios from 'axios'
import { getToken } from "@/xxx";
import ElementUI from 'element-ui';
export function getOutExcel(url, data, method = "post") {
axios({
headers: {
Authorization: getToken(),
"Content-type": "application/json; charset=utf-8",
},
method: method || 'post',
baseURL: process.env.VUE_APP_BASE_API,
url: url,
data: method === 'post' ? data : null,
params: method === 'get' ? data : null,
responseType: "blob",
}).then((res) => {
const content = res.data;
const blob = new Blob([content]);
const fileName = `模板.xls`;
if ("download" in document.createElement("a")) {
const elink = document.createElement("a");
elink.download = fileName;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href);
document.body.removeChild(elink);
} else {
navigator.msSaveBlob(blob, fileName);
}
}).catch(err => {
ElementUI.Message({
message: '导出失败',
type: 'error'
});
});
}
调用
<template>
<div>
<span @click="downLoad">下载模板</span>
</div>
</template>
import { getOutExcel} from "@/utils/xxx"
methods:{
downLoad(){
getOutExcel('第一个参数写接口的地址','接口需要的参数','请求类型 默认post')
}
}