今天碰到一个问题,创建一个下载模板按钮,平平无奇的功能代码如下
ini
`
<!--template -->
...
<DButton
v-for="(templateUrl, index) in templateUrls"
:key="index"
link
type="primary"
:icon="Download"
@click="templateUrl.url()"
>
{{ templateUrl.label }}
</DButton>
...
<!--js-->
url: async () => {
try {
// const blob = await (serversApis.servers as any).knowledgeQaTemplate({ responseType: 'blob' })
// // 兼容 axios 封装:可能直接返回 Blob 或 { data: Blob }
// const data: Blob = (blob instanceof Blob) ? blob : (blob?.data ?? blob)
// const url = URL.createObjectURL(data)
// const a = document.createElement('a')
// a.href = url
// a.download = '问答导入模板.xlsx'
// document.body.appendChild(a)
// a.click()
// a.remove()
// URL.revokeObjectURL(url)
//this is right code,no need to create a.click()
await (serversApis.servers as any)
.knowledgeQaTemplate({ responseType: 'blob' })
}
catch (e) {
ElMessage.error('模板下载失败')
// 控制台打印方便排查
console.error('knowledgeQaTemplate 下载失败:', e)
}
},`
看日志也是事件和请求只执行了一次,好一顿找,最后发现是响应头有这个:
Content-Disposition:attachment;filename*=%E7%9F%A5%E8%AF%86%E5%BA%93%E9%97%AE%E7%AD%94%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx

所以直接改方法只执行请求方法即可:
url: async () => { try { // const blob = await (serversApis.servers as any).knowledgeQaTemplate({ responseType: 'blob' }) // // 兼容 axios 封装:可能直接返回 Blob 或 { data: Blob } // const data: Blob = (blob instanceof Blob) ? blob : (blob?.data ?? blob) // const url = URL.createObjectURL(data) // const a = document.createElement('a') // a.href = url // a.download = '问答导入模板.xlsx' // document.body.appendChild(a) // a.click() // a.remove() // URL.revokeObjectURL(url) //this is right code,no need to create a.click() await (serversApis.servers as any) .knowledgeQaTemplate({ responseType: 'blob' }) } catch (e) { ElMessage.error('模板下载失败') // 控制台打印方便排查 console.error('knowledgeQaTemplate 下载失败:', e) } },
完美!!!!