js下载、导出功能,不打开新窗口

<el-button type="primary" @click="onExport">导 出</el-button>
methods: {
  onExport() {
    // 此处做想做的事情,然后调用download方法,并将服务端下载链接传过去
    this.download(src);
  },  
// 第一种方法通过隐藏的iframe标签实现
  download(src) {
    this.$nextTick(() => {
        if (typeof this.download_file.iframe == 'undefined') {
          const iframe = document.createElement('iframe');
          this.download_file.iframe = iframe;
          document.body.appendChild(this.download_file.iframe);
        }
        const { iframe } = this.download_file;
        iframe.src = src;
        iframe.style.display = 'none';
        // 若下载链接有效时间为5分钟
        const timer = setTimeout(() => {
          document.body.removeChild(this.download_file['iframe']);
          delete this.download_file['iframe'];
          clearTimeout(timer);
        }, 5 * 60 * 1000);
      });
    },
// 第二种方法通过隐藏的a标签实现
  download(src) {
    this.$nextTick(() => {
        if (typeof this.download_file.a == 'undefined') {
          const a = document.createElement('a');
          this.download_file.a = a;
          document.body.appendChild(this.download_file.a);
        }
        const { a } = this.download_file;
        a.href = src;
        a.style.display = 'none';
        a.click();
        // 若下载链接有效时间为5分钟
        const timer = setTimeout(() => {
          document.body.removeChild(this.download_file['a']);
          delete this.download_file['a'];
          clearTimeout(timer);
        }, 5 * 60 * 1000);
      });
    },
},

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。