vue+elementui实现导出Excel⽂件⾸先,⼀定⼀定要设置请求头:responseType: 'blob',
⼀开始试了⼀下直接调⽤的,就是像平常调⽤接⼝那样,发现返回来⼀堆乱码,所以,
const link = ateElement('a')
link.download = fileName
link.href = objectUrl
link.click()
也是关键
其他位置像正常连接⼝那样写就可以了,我是这样写的,封装好的接⼝:
<el-button type="primary" class="refresh" @click="onCheckedOut">导出</el-button>
import {exportData} from 'config/index'
onCheckedOut () { // 导出
exportData({
url: '/admin/user/info/export'
}).then(res => {
vue element admin if (res.status == 200) {
let fileName = res.headers['content-disposition'].split('=')[1]
let objectUrl = ateObjectURL(new Blob([res.data]))
const link = ateElement('a')
link.download = fileName
link.href = objectUrl
link.click()
} else {
this.$('出现异常请联系管理员!')
}
}).catch(err => {
this.$('出现异常稍后再试!')
})
}
config/index.js
export const exportData = ({ url, data }) => { // 导出⽂件使⽤
return httpDowload({ url, data, method: 'post' })
}
export const httpDowload = httpParams => {
let { url, data, method } = { url: '', data: {}, method: 'get', ...httpParams }
try {
let params = {}
if (method === 'get') {
params = data
data = {}
}
return axios({
baseUrl: httpParams.baseURL || '/admin',
url,
method,
params,
data,
headers: setHeaders(),
responseType: 'blob'
}).then((zData) => handleResponse(zData))
} catch (err) {
console.log(err)
}
}
function handleResponse (data) {
if (data.status !== 200) {
ject(data)
} else {
solve(data)
}
}
export function setHeaders () {
const token = Item('token') === null ? '' : Item('token')
return {
TOKEN: token
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论