1.创建一个js文件,封装导出的接口,里面的内容如下
// 导出Excel公用方法
import axios from 'axios'
export function exportMethod(data) {
axios({
method: data.method,
url: `${data.url}${data.params ? '?' + data.params : ''}`,
responseType: 'blob'
}).then((res) => {
const link = document.createElement('a')
let blob = new Blob([res.data], {type: 'application/vnd.ms-excel'})
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
link.download = data.fileName //下载的文件名
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}).catch(error => {
this.$message.error('网络错误')
console.log(error)
})
}
2.在需要使用的页面中引入
import { exportMethod } from "../../utils/exportMethod.js";
3.使用
handleAddClick() { //点击导出调封装好的方法
let myObj = {
method: "get",
url: "",
fileName: this.formatTime(new Date(), "yyyy-MM-dd hh-mm"), //下载好的文件名称,我这里是用的当前时间
params:``, //接口参数
};
exportMethod(myObj);
},