在Vue.js中,如果你需要在一个按钮点击事件里同时导出两个接口返回的文件,你可以使用axios
或其他HTTP库来发送请求,并使用Blob
对象来处理文件下载。以下是一个示例代码,展示了如何实现这一功能:
<template>
<button @click="exportFiles">导出文件</button>
</template>
<script>
import axios from 'axios';
export default {
methods: {
async exportFiles() {
try {
// 发送第一个请求
const response1 = await axios.get('/api/export/file1', {
responseType: 'blob' // 指定响应类型为Blob
});
// 发送第二个请求
const response2 = await axios.get('/api/export/file2', {
responseType: 'blob' // 指定响应类型为Blob
});
// 创建Blob对象并下载第一个文件
const url1 = window.URL.createObjectURL(new Blob([response1.data]));
const link1 = document.createElement('a');
link1.href = url1;
link1.setAttribute('download', 'file1.xlsx'); // 设置下载文件名
document.body.appendChild(link1);
link1.click();
// 创建Blob对象并下载第二个文件
const url2 = window.URL.createObjectURL(new Blob([response2.data]));
const link2 = document.createElement('a');
link2.href = url2;
link2.setAttribute('download', 'file2.xlsx'); // 设置下载文件名
document.body.appendChild(link2);
link2.click();
// 清理DOM
document.body.removeChild(link1);
document.body.removeChild(link2);
window.URL.revokeObjectURL(url1);
window.URL.revokeObjectURL(url2);
} catch (error) {
console.error('导出文件失败:', error);
}
}
}
};
</script>
发送请求:使用axios.get
发送两个请求,分别获取两个文件。responseType: 'blob'
指定响应类型为Blob
,以便处理二进制文件。
创建Blob对象:使用new Blob([response.data])
将响应数据转换为Blob
对象。
创建下载链接:使用window.URL.createObjectURL
创建一个临时的URL,并将其赋值给<a>
标签的href
属性。
触发下载:通过link.click()
触发文件下载。
清理DOM:下载完成后,移除创建的<a>
标签,并释放URL
对象以释放内存。
.xlsx
和.pdf
),请根据实际情况设置download
属性中的文件名和扩展名。通过这种方式,你可以在一个按钮点击事件中同时导出两个接口返回的文件。