1.新增一个js文件(downloadFile.js)
import { _axios } from "../assets/request";
import Vue from "vue";
//url为导出的地址
//fileName为导出的文件名称
//methods是使用post或者get方法请求
function downloadFile(url,fileName,methods) {
if(methods=="post"){
_axios.post(url, { responseType: 'blob' }).then(res => {
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel; charset=utf-8' })
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = fileName //下载的文件名称
link.click()
URL.revokeObjectURL(link.href)
Vue.prototype.$message({
message: "导出成功~",
type: "success",
});
}).catch(err => {
console.log(err,"导出失败的错误信息")
Vue.prototype.$message({
message: "导出失败~",
type: "error",
});
})
}else{
_axios.get(url, { responseType: 'blob' }).then(res => {
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel; charset=utf-8' })
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = fileName //下载的文件名称
link.click()
URL.revokeObjectURL(link.href)
Vue.prototype.$message({
message: "导出成功~",
type: "success",
});
}).catch(err => {
console.log(err,"导出失败的信息")
Vue.prototype.$message({
message: "导出失败~",
type: "error",
});
})
}
}
export {downloadFile}
2.在页面引入封装的js文件
import { downloadFile } from "../../assets/downloadFile"
3.使用
exportEXL() {
downloadFile(`地址`, "需要导出的文件名", "接口请求方法(get/post)")
},