vue axios cancelToken 取消上一次请求,在离开当前页面时取消全部请求

data() {
return {
cancelRequest: null
}
}
初始化的时候只能在一个方法里面写,不然会把其他的请求阻止了
if (typeof that.cancelRequest === "function") {
that.cancelRequest();
}
const CancelToken = axios.CancelToken
axios.get(url, {
params:params,
cancelToken: new CencalToken(function executor(c) {
_this.cancelRequestList = c
Vue.httpRequestList.push(c) // 把所有的请求放在一个数组里面 }) }) // executor 里面有cancel token两个方法 main.js Vue.httpRequestList = []

router.js
import { clearHttpRequestingList } from '../utils/clearHttpRequestingList'
router.beforeEach((to, from, next) => {
clearHttpRequestingList() // 取消所有请求
})

clearHttpRequestingList.js

improt Vue from 'vue'

exprot const clearHttpRequestingList = () => {
if(Vue.httpRequestList.length > 0) { Vue.httpRequsetList.forEach((item) => {
item()
})
Vue.$httpRequestList = []
}
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容