功能: 点击导出按钮, 提交请求, 下载 excel 文件;
第一步: 跟后端童鞋确认交付的接口的 response header 设置了
以及返回了文件流
第二步: 修改 axios 请求的 responseType 为 blob, 以 post 请求为例:
- axios({
- method: post,
- url: api/user/,
- data: {
- firstName: Fred,
- lastName: Flintstone
- },
- responseType: blob
- }).then(response => {
- this.download(response)
- }).catch((error) => {
- })
第三步: 请求成功, 拿到 response 后, 调用 download 函数 (创建 a 标签, 设置 download 属性, 插入到文档中并 click)
- methods: {
- // 下载文件
- download (data) {
- if (!data) {
- return
- }
- let url = window.URL.createObjectURL(new Blob([data]))
- let link = document.createElement(a)
- link.style.display = none
- link.href = url
- link.setAttribute(download, excel.xlsx)
- document.body.appendChild(link)
- link.click()
- }
- }
来源: http://www.bubuko.com/infodetail-2513144.html