1.使用vuex全局变量存取
const store = new Vuex.Store ({
state: {
axiosCancelArr: []
},
mutations: {
PUSH_CANCEL(state, cancel) {
state.axiosCancelArr.push(cancel.cancelToken)
},
CLEAR_CANCEL(state) {
state.axiosCancelArr.forEach(e => {
e && e()
})
state.axiosCancelArr = []
}
},
actions: {
pushCancel({ commit }, cancel) {
commit('PUSH_CANCEL', cancel)
},
clearCancel({ commit }) {
commit('CLEAR_CANCEL')
}
}
})
export default store
2.request.js关键代码
//请求拦截器
axios.interceptors.request.use(res => {
res.cancelToken = new axios.CancelToken(cancel => {
store.dispatch('pushCancel', { cancelToken: cancel })
})
})
//响应拦截器
axios.interceptors.response.use(res => {
const data = res.data
//判断是否取消后续请求
if (data.code === '401') {
store.dispatch('clearCancel')
}
})
3.使用路由拦截器,跳转路由时调用clearCancel方法,清空存入的信息,终止未请求成功的请求
router.beforeEach((to, from, next) => {
store.dispatch('clearCancel')
next()
})