后台管理系统中会有很多导出文件的地方,总结两种方式
window.open()
这种方式简单,会打开一个新的新的标签页,并且加载指定资源,但当标签页关闭的时候会感觉页面抖动了一下。
通过向dom中添加a标签
不会打开标签页,但需要操作dom
function downloadFile(id) {
const domA = document.createElement('a')
domA.setAttribute('id', 'createId')
domA.setAttribute('href', `download?id=${id}`)
// 防止反复添加
if (document.getElementById('createId')) {
document.body.removeChild(document.getElementById('createId'))
}
document.body.appendChild(domA)
domA.click()
document.body.removeChild(domA)
}