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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章