济南微信网站,WordPress页码总数,做app网站建设,服务器租用价格在 Vue 3 中#xff0c;你可以使用 axios 或 fetch 来下载文件#xff0c;并将 responseType 设置为 blob 以处理二进制数据。以下是一个使用 axios 的示例#xff1a; 
使用 axios 下载文件 首先#xff0c;确保你已经安装了 axios#xff1a; npm install axios然后在你…在 Vue 3 中你可以使用 axios 或 fetch 来下载文件并将 responseType 设置为 blob 以处理二进制数据。以下是一个使用 axios 的示例 
使用 axios 下载文件 首先确保你已经安装了 axios npm install axios然后在你的 Vue 组件中使用 axios 下载文件 templatebutton clickonDownloadClick下载文件/button
/templatescript
import { handleFileExport } from /utils/exportExcel;
import { apiGetDownload } from /api/encouragementApi;export default {methods: {function onDownloadClick(row: any) {const response  await axios.get(https://example.com/path/to/file, {responseType: blob, // 重要设置响应类型为 blob});.handleFileExport(response )setTimeout(()  {ElMessage.success(下载成功)}, 1000)}},
};
/script在utils/exportExcel.ts 
// 后端接口导出 非同源的资源需要下载可以将其转换为Blob:Url
const handleFileExport  (res:any)  {
if(res.request.responseTypeblob){let contentDisposition  res.headers[content-disposition]if (!contentDisposition) {contentDisposition  ;filename${decodeURI(res.headers.filename)};}const fileName  window.decodeURI(contentDisposition.split(filename)[1]);const blob  new Blob([res.data], {type: text/xlsx,});let downloadUrl  window.URL.createObjectURL(blob);let a  document.createElement(a);a.style.display  none;a.href  downloadUrl;a.download  fileName;let event  new MouseEvent(click);a.dispatchEvent(event);
}
};使用a标签下载 const url  apiDownloadImportFileStr({encourageTypeId: 1})const link  document.createElement(a)link.href  urllink.click()关键点 
responseType: blob这是告诉 axios 或 fetch 返回一个 Blob 对象用于处理二进制数据。window.URL.createObjectURL创建一个临时的 URL用于下载文件。 
注意事项 
确保服务器支持跨域请求CORS否则可能会遇到跨域问题。如果文件较大可能需要考虑分块下载或显示下载进度。 
通过这些步骤你可以在 Vue 3 中实现文件下载功能。