axios请求封装
function http(config) {
// axios的默认配置 如果时get 参数需要放到 params
// 如果是post 参数需要放到 data
var myConfig = {
url: config.url,
method: config.method,
header: {},
responseType: config.responseType || ‘‘
}
if (config.method.toLowerCase() == ‘post‘) {
myConfig.data = config.params
} else if (config.method.toLowerCase() == ‘get‘) {
myConfig.params = config.params
}
if (config.header) {
myConfig.header = Object.assign(myConfig.header, config.header);
}
// 区分了get和post 的配置
//service就是axios
return service(myConfig)
}
export default http
接口封装
import request from ‘@/api/http‘
//导出老师信息
function exportTeachers(params) {
return request({
url: ‘/web/teacher/exportTeachers‘,
method: ‘post‘,
headers: { ‘content-type‘: ‘application/vnd.ms-excel;charset=utf-8‘ },
responseType: ‘arraybuffer‘,
params
})
}
export default {
exportTeachers
}
页面代码
exportTeachers() {
let data = {
schoolCode: this.schoolNumber,
enrollmentYear: this.filterGradeTeacher.enrollmentYear || ‘‘,
classId: this.filterClassTeacher.id || ‘‘
}
techerApi.exportTeachers(data).then(res => {
//解析
const url = window.URL.createObjectURL(new Blob([res]))
const link = document.createElement(‘a‘)
link.style.display = ‘none‘
link.href = url
link.setAttribute(‘download‘, `老师信息.xls`)
document.body.appendChild(link)
link.click()
})
},
注意:导出的xls文件内容一直为undefined,经过多次尝试需加上responseType: ‘arraybuffer‘才行,具体还是得根据后端.