当vue切换页面时,尚未完成的接口由于异步原因,会造成报错等等问题,那么这时需要去取消这些接口的执行
首先思路:
页面A请求接口axios1 -->
axios创建CancelToken对象保存请求至store变量CancelTokenArr -->
当切换至页面B -->
进入全局路由守卫调用vuex的清除CancelTokenArr方法 -->
遍历CancelTokenArr清除
涉及的库
- axios
- vuex
- vue-router
++axios++
import store from '../store'
let cancelTokenArr=[] //储存cancel token
// request拦截器
service.interceptors.request.use(
config => {
if (store.getters.token) {
config.headers['X-Token'] = getToken()
// 在发送请求设置cancel token
config.cancelToken = new axios.CancelToken(cancel => {
store.commit('PUSH_CANCEL', {
cancelToken: cancel
})
})
}
return config
},
error => {
console.log(error) // for debug
Promise.reject(error)
}
)
++vuex++
const axios = {
state: {
cancelTokenArr: []
},
mutations: {
PUSH_CANCEL(state, payload){
state.cancelTokenArr.push(payload.cancelToken);
},
CLAER_CANCEL({cancelTokenArr}){
cancelTokenArr.forEach(item => {
item('路由跳转取消请求');
});
cancelTokenArr = [];
}
}
}
export default user
++router++
import store from './store'
router.beforeEach((to, from, next) => {
store.commit('CLAER_CANCEL'); // 取消请求
next()
})
网友评论