如何在Nuxt前端展示Rails API返回的application/pdf类型响应
方案1:新标签页预览PDF(最常用)
你已经正确配置了responseType: 'blob',拿到返回值后直接生成Blob临时URL即可打开预览:
const params = { name: "myName", address1: "Tokyo", address2: "Minato-ku" } const config = { responseType: 'blob', } const res = await this.$axios.post('/v1/orders', params, config) // 生成临时URL,res.data本身就是Blob对象,无需重复构造 const pdfUrl = window.URL.createObjectURL(res.data) // 新标签页打开预览 window.open(pdfUrl, '_blank') // 可在不需要时释放内存,比如页面销毁钩子中调用 // window.URL.revokeObjectURL(pdfUrl)
如果需要直接下载而不是预览,用a标签模拟点击即可:
const pdfUrl = window.URL.createObjectURL(res.data) const link = document.createElement('a') link.href = pdfUrl link.download = '订单凭证.pdf' // 自定义下载文件名 link.click() // 下载完成后立即释放内存 window.URL.revokeObjectURL(pdfUrl)
方案2:内嵌到当前页面展示
如果需要把PDF嵌入当前页面的指定区域,用embed或iframe标签实现即可:
模板部分
<template> <div class="pdf-container"> <embed v-if="pdfUrl" :src="pdfUrl" type="application/pdf" width="100%" height="800px" /> <!-- 也可以用iframe标签,用法一致 --> <!-- <iframe v-if="pdfUrl" :src="pdfUrl" width="100%" height="800px" /> --> </div> </template>
逻辑部分
export default { data() { return { pdfUrl: '' } }, methods: { async loadPdf() { const params = { name: "myName", address1: "Tokyo", address2: "Minato-ku" } const config = { responseType: 'blob', } const res = await this.$axios.post('/v1/orders', params, config) this.pdfUrl = window.URL.createObjectURL(res.data) } }, beforeDestroy() { // 页面销毁时释放临时URL占用的内存 if (this.pdfUrl) { window.URL.revokeObjectURL(this.pdfUrl) } } }
注意事项
- 临时URL仅在当前页面会话有效,刷新页面后会自动失效,无需持久化存储
- 部分老旧浏览器不支持内嵌标签预览PDF,这类场景优先使用新标签页打开的方案
- 如果出现跨域问题,检查Rails后端的CORS配置是否已经放行当前Nuxt域名的请求
内容的提问来源于stack exchange,提问作者batch
相关产品推荐
相关产品推荐

