在VUE中--导出json文件,前端请求接口返回一堆json数据,如何导出成json文件并且下载???

areaButton(){
      // 点击下载  
      outArea().then(res=>{   
        var data = JSON.stringify(res) 
        //encodeURIComponent解决中文乱码
        let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(data);
        //通过创建a标签实现
        let link = document.createElement("a");
        link.href = uri;
        //对下载的文件命名
        link.download =  "地区数据表.json";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
    },

 

 

 参考链接:https://blog.csdn.net/xxxxxxxxYZ/article/details/94572687

 

如果是文件流或者链接的话(不要求token值)

// 点击下载(预览查看)
    onPreview(file) {
      const a = document.createElement('a')
      a.href = `${window.config1}/annex/annexDownload?id=${file.id}`
      a.download = file.name
      a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))
    },

 项目中实际应用的

const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
            const url = window.URL.createObjectURL(blob)
            var filename = '订单列表'
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', filename + '.xls')
            document.body.appendChild(link)
            link.click()

 

不要忘记在请求时加上responseType:'blob

 

posted @ 2020-07-09 22:14  小白呀白菜  阅读(4440)  评论(0编辑  收藏  举报