vue+axios封装一个文件流导出

  • 在main.js里全局注册组件
import Download from '@/components/DownLoad/index'
Vue.component('Download', Download);
  • 在app.vue文件中引入
<template>
	 <div class="energy-index-wrap qry-index-wrap">
      	<el-button type="export" @click="ExportData">导出</el-button>
     </div>
     <down-load
      ref="downLoad"
      excelName="报表"
      url="你的导出接口地址"  
      :params="qryForm"
    />
<template>
import DownLoad from '@/components/DownLoad/index'
export default {
  components: {
    'down-load': DownLoad
  },
  data() {
    return {
    // 导出参数
      qryForm: {
        useOrgId: '',
        equipSystemCode: '',
      }
    }
  },
  methods: {
    /*
     * 导出数据
     * */
    async ExportData() {
      this.$refs.downLoad.downLoad()
    }
  }
}	
  • DownLoad/index文件
<template></template>
<script>
import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '@/store'
import { parseTime } from '@/utils/index'
let fileName = '' // 文件名
let loadingInstance = {
  close: function() {}
}
const timeout = 20000 // 请求超时,适当修改
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout
})
// http request 拦截器
service.interceptors.request.use(
  config => {
    loadingInstance = Loading.service({
      lock: true,
      text: '正在导出,请耐心等待.....',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    config.headers['Authorization'] = store.getters.token || ''
    return config
  },
  error => {
    window.console.error(error)
    return Promise.reject(error)
  }
)

// http response 拦截器
service.interceptors.response.use(
  res => {
    loadingInstance.close()
    processData(res.data)
    res.data = ''
    return res
  },
  error => {
    loadingInstance.close()
    window.console.error(error)
    return Promise.resolve(error.response)
  }
)
/*
 *  处理文档数据
 * */
function processData(data) {
  if (!data) {
    return
  }
  const url = window.URL.createObjectURL(new Blob([data]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/*
 *  通过 axios ajax 请求资源
 * */
function ajax(url, method, data = {}) {
  let paramStr = ''
  for (const p in data) {
    paramStr += '&' + p + '=' + data[p]
  }
  paramStr && (url += '?' + paramStr.slice(1))
  service({
    method,
    url,
    data: data,
    responseType: 'blob'
  })
    .then(res => {
      res = res || { status: 404, statusText: '服务器出错!' }
      if (res.status === 200 || res.status === 304 || res.status === 400) {
        return res
      }
    })
    .catch(err => {
      Message({
        message: `导出有问题,${err}`,
        type: 'error',
        duration: 2 * 1000
      })
      window.console.log('代码有问题:', err)
    })
}

export default {
  name: 'DownLoad',
  props: {
    url: {
      type: String,
      default: ''
    },
    excelName: {
      type: String,
      default: ''
    },
    fileName: {
      type: String,
      default: ''
    },
    params: {
      type: Object,
      default: function() {
        return {}
      }
    },
    method: {
      type: String,
      default: 'post'
    }
  },
  methods: {
    downLoad(params) {
      this.$nextTick(() => {
        // 延迟下载,保证params参数获取
        const nowTime = parseTime(new Date(), '{mm}-{dd} {hh}_{ii}_{ss}')
        Object.assign(this.params, params)
        let excelName = this.excelName
        if (!excelName.includes('.xls')) {
          excelName += '.xlsx'
        }
        fileName = this.fileName || excelName || 'excel.xlsx'
        fileName = fileName.replace(/(\.\w+)$/, '(' + nowTime + ')$1')
        this.params.excelName && delete this.params.excelName
        this.params.fileName && delete this.params.fileName
        ajax(this.url, this.method, this.params)
      })
    }
  }
}
</script>
<style scoped>
</style>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值