美文网首页
vue导出功能

vue导出功能

作者: Light_shallow | 来源:发表于2019-11-01 17:00 被阅读0次

    后台返回的有两种情况,一种是流,另一种是地址 ,下面分别来说
    1、第一种后台返回地址

         exportData() {
            exportDataDeal(this.form).then(data => {
              if(data.status == 200){
                this.download(data.request.responseURL);
              }
            });
          },
          download(url) {
            var iframe = document.createElement("iframe")
            iframe.style.display = "none";
            iframe.src = url;
            document.body.appendChild(iframe);
          },
    

    2、后台返回的是流
    // 利用iframe 封装的方法
    //options这个对象里面有两个key,action和data

    action是地址 data 是接口需要的传参
    export const postDownLoadFile = function(options) {
        let config = { method: 'post', ...options };
        let $iframe = document.getElementById('down-file-iframe');
        if (!$iframe) {
            $iframe = document.createElement('iframe');
        }
        let $form = document.createElement('form');
        $form.setAttribute('target', 'down-file-iframe');
        $form.setAttribute('method', config.method);
        $form.setAttribute('action', `${baseUrl[process.env.NODE_ENV]||""}/${config.action}`);
        for (var key in config.data) {
            let $input = document.createElement('input');
            $input.setAttribute('type', 'hidden');
            $input.setAttribute('name', key);
            $input.setAttribute('value', config.data[key]);
            $form.appendChild($input);
        }
        $iframe.appendChild($form);
        document.body.appendChild($iframe);
        $iframe.getElementsByTagName('form')[0].submit();
        document.body.removeChild($iframe);
    }
    
    

    // 利用form

    <form :method="method || 'POST'" v-show="false" :action="url" id="hiddenForm" ref="hiddenForm" target="_blank">
                <input type="text" v-for="item in params" :key="item.key" :name="item.key" :value="item.val" />
                <input type="submit" value="提交">
            </form>
    // 再调用它的submit方法就可以了
    

    // 直接用原生方法

    orderListInfo.exportInfo().then(response => {
            if (response) {
              const aLink = document.createElement('a')
              const newfileName = response.headers['content-disposition'].split('=')[1]
              let blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
              aLink.href = URL.createObjectURL(blob)
              aLink.setAttribute('download', `${newfileName}`)
              aLink.click()
              window.URL.revokeObjectURL(blob)
            } else {
              this.$message({ showClose: true, message: response.errMsg || '查询失败', type: 'warning' })
            }
          }).catch(error => {
            console.log(error)
          })
    

    相关文章

      网友评论

          本文标题:vue导出功能

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