美文网首页
js下载、导出功能,不打开新窗口

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

作者: 一爷之秋 | 来源:发表于2020-01-09 14:48 被阅读0次
<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);
      });
    },
},

相关文章

网友评论

      本文标题:js下载、导出功能,不打开新窗口

      本文链接:https://www.haomeiwen.com/subject/eumyactx.html