下载按钮点击一次却下载两个文件问题

今天碰到一个问题,创建一个下载模板按钮,平平无奇的功能代码如下

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) } },

完美!!!!

相关推荐
এ慕ོ冬℘゜17 分钟前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
武子康26 分钟前
Search Console Platform Properties 扩大 SEO 资产边界:从 Page Ranking 到 Topic Coverage(5 类误读边界 + 3 表数据层设计)
前端·人工智能·后端
一点一木1 小时前
从60首歌到1个网站:输入你的故事,还你一首歌
前端·github
IT_陈寒2 小时前
Vue这个特性差点让我加班到凌晨,谁懂啊
前端·人工智能·后端
kyriewen2 小时前
我让AI改一个bug——它偷偷动了5个我没让它碰的地方
前端·javascript·ai编程
遇乐的果园3 小时前
前端学习笔记-vue加载渲染优化
前端·笔记·学习
用户985033593284 小时前
OpenLayers 热力图从原理到 Vue 组件一键接入
前端
颜酱4 小时前
01 | 骨架搭建:FastAPI + Vue 跑通第一个 SSE 流式问答
前端·人工智能·后端
hoLzwEge4 小时前
解码 IDE 智能提示:jsconfig.json 辅助开发全攻略
前端·前端框架
leoZ2314 小时前
记忆系统与 Agent 定制完全指南(四):自定义 Agent 开发(一)
前端·chrome