vueelementUIvue

vue element-UI 实现导出excel 功能

2023-03-09  本文已影响0人  Moment929

前端项目实现请求后台接口

步骤一:安装axios组件,一般使用命令:npm install axios --save
步骤二:为了项目规范整洁,把一些配置请求后台统一前缀,以及一些拦截器,代码如下(文件在@/utils/request)
import axios from 'axios'

// create an axios instance
const service = axios.create({
  baseURL: 'http://10.246.34.23:10000',
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'TOKEN ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    if (res.code !== 0) {
      // 处理下载文件流
      if (res instanceof Blob) {
        return response
      }
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
步骤三:编写统一存放API地址文件,并且传参数指定请求方式(文件在'@/api/account):
// 交易账号列表下载
export function accountDownload(query) {
  return request({
    url: '/transaction-account/information-maintenance/download',
    method: 'get',
    responseType: 'blob',
    params: query
  })
}

****** 在和后台交互的时候,如果后台返回给我们的是二进制流数据,我们就要在发送的时候加上{responseType:'blob'}这行代码,这样返回数据给我们的就不是乱码了。

步骤四:Vue页面调用API接口,并且实现文件下载
<template>
<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-download" @click="exportExcel">
      导出账号信息
</el-button>
</template>

<script>
import { accountDownload } from '@/api/account'

export default {
  methods: {
    exportExcel () {
      accountDownload().then(response => {
        if (response) {
          // 创建URL
          let url = window.URL.createObjectURL(new Blob([response.data]))
          // 插入一个a标签,隐藏,设置href属性,触发点击方法
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '导出账号信息.xlsx')
          document.body.appendChild(link)
          link.click()
          
          //下载完成后
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
        }
       
      })
    }
  }
}

记录碰到的问题,让自己更进一步

上一篇下一篇

猜你喜欢

热点阅读