引入
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import { saveAs } from 'file-saver'
import axios from 'axios'
接口封装
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 10000,
})
export function download(url, params, filename, config) {
downloadLoadingInstance = Loading.service({
text: '正在下载数据,请稍候',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)',
})
return service
.post(url, params, {
transformRequest: [
(params) => {
return tansParams(params)
},
],
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
responseType: 'blob',
...config,
})
.then(async (data) => {
const isLogin = await blobValidate(data)
if (isLogin) {
const blob = new Blob([data])
saveAs(blob, filename)
} else {
const resText = await data.text()
const rspObj = JSON.parse(resText)
const errMsg =
errorCode[rspObj.code] || rspObj.msg || errorCode['default']
Message.error(errMsg)
}
downloadLoadingInstance.close()
})
.catch((r) => {
console.error(r)
Message.error('下载文件出现错误,请联系管理员!')
downloadLoadingInstance.close()
})
}
全局挂载
import Vue from 'vue'
import { download } from '@/utils/request'
Vue.prototype.download = download
使用
async Exports() {
this.download(
'接口路径',
{},
`导出表${new Date().getTime()}.xlsx`
)
},