封装点击下载功能

一、下载流程

调用下载接口

创建a标签

创建下载链接

将a;标签添加到bodiy中

添加点击事件,进行下载

下载完成移除a标签

释放掉blod对象

二、封装

download.js

export function download2(data, fileName) {
//throw关键字自定义抛出错误
if (!data) throw new Error('arguments is not null!'); let blob = new Blob([data]); window.URL = window.URL || window.webkitURL; let url = window.URL.createObjectURL(blob); let link = document.createElement('a'); link.style.display = 'none'; link.href = url; link.setAttribute('download', fileName); document.body.appendChild(link); link.click(); window.URL.revokeObjectURL(url); }

download.vue使用

import { download} from '@/common/download.js';
async downloadTheReport () {
      this.downloading = true;
//请求
      let res = await adsApi.downloadTheReport();
      this.downloading = false;
//res后端返回的数据
      download2(res.data, `下载报告.xlsx`);
      this.downloading = false;
    }

 

posted @ 2022-02-07 18:45  前端乔  阅读(58)  评论(0编辑  收藏  举报