【vue】---- 前端实现下载Excel功能

1、实现思路:

html5 中,在 a 标签上添加 download 属性可以实现文件下载。

<a download="文件名" href="文件下载接口地址"></a>

2、在这次项目中,点击非a标签按钮下载文件,通过创建a标签来实现。

<script>
  export default {
    data() {
      return {
        downFileName: 'user_dowm',  // 自定义下载的文件名
      }
    },
    methods:{
// 点击下载事件 downLoadFail(data) { this.$axios({ headers: { 'Content-Type': 'application/json' }, url: '/user/download', data: data, responseType: 'blob', method: 'get' }).then(res => { if (typeof window.chrome !== 'undefined') { // Chrome version const blob = new Blob([res], { type: 'application/vnd.ms-excel' }) const urls = window.URL.createObjectURL(blob) const a = document.createElement('a') // 生成虚拟a标签 a.href = urls a.download = this.downFileName + '.xlsx' a.click() document.body.removeChild(a) // 下载完成移除元素 window.URL.revokeObjectURL(urls) // 释放掉blob对象 } else if (typeof window.navigator.msSaveBlob !== 'undefined') { // IE version const blob = new Blob([res], { type: 'application/force-download' }) window.navigator.msSaveBlob(blob, this.downFileName) } else { // Firefox version const file = new File([res], this.downFileName, { type: 'application/force-download' }) window.open(URL.createObjectURL(file)) } }).catch(err => { console.log(err) }) } } } </script>

注:发现一篇实用的前端下载文件的参考,贴上~

https://www.jianshu.com/p/48ad4346fe4b