一、定义导出接口时,多传一个options
export const exportApi = (url, data, options) => {
return axios({
url,
method: 'post',
responseType: 'blob',
headers: { loading: false },
data,
...options
})
}
二、利用 CancelToken 构造函数,保存一个取消请求的函数(cancel)
import axios from 'axios'
let cancel = null
...
setLoading(true)
exportApi(exportUrl, exportParams, {
cancelToken: new axios.CancelToken(c => (cancel = c))
})
.then(data => {
const blob = new Blob([data])
const objectURL = URL.createObjectURL(blob)
let btn = document.createElement('a')
btn.download = title
btn.href = objectURL
btn.click()
URL.revokeObjectURL(objectURL)
btn = null
setPercent(99)
message.success('下载成功')
setLoading(false)
})
.catch(error => {
console.log('导出接口出错', error)
message.error('取消批量导出')
setLoading(false)
})
三、当点击【取消】按钮时,调用 cancel 方法
const handleColse = () => {
console.log('handleColse', cancel)
onCancel()
clearInterval(timer.current)
if (cancel) {
cancel('取消请求')
cancel = null
}
}