HTML代码: <el-button size="medium" @click="download">下载表格</el-button>
js代码:
<script>
import fileDownload from 'js-file-download' //下载js-file-download:npm install js-file-download
methods: { //下载表格 downloadHttpRequest(u, json, success, fail) { this.$http({ method: "post", url: u, data: json, headers: { "Content-type": "application/json", "Access-Control-Allow-Methods": "*", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": ["x-requested-with", "content-type"] }, responseType: "blob" }) .then(res => { let resBlob = res.data // <--- store the blob if it is let resData = null let filename = 'attach.txt'; //给下载文件命名 try { let resText = new Promise((resolve, reject) => { let reader = new FileReader() reader.addEventListener('abort', reject) reader.addEventListener('error', reject) reader.addEventListener('loadend', () => { resolve(reader.result) }) reader.readAsText(resBlob) }) resData = JSON.parse(resText) // <--- try to parse as json evantually } catch (err) { // ignore } if (resData) { if (resData.error) { // handle error } else { // handle data } } else { // handle blob fileDownload(resBlob, filename) } }); }, download() { let _this = this; //下载表格接口/passport/getPassportNumberAndCode _this.downloadHttpRequest( "/ARPassport/passport/getPassportNumberAndCode", { code: 0, data: _this.$route.query.id }, function success(res) { }, function fail(err) { } ); } }
</script>
此方法参考了网上的资料