vue-router路由切换取消上一页的所有axios请求

768 阅读1分钟

根据config生成url(key)

function createdUrl (config: any) {
  return [
    config.method,
    config.url,
    JSON.stringify(config.params),
    JSON.stringify(config.data)
  ].join('&')
}

axios拦截

// 请求拦截器
axios.interceptors.request.use(config => {
    const url = createdUrl(config)
    for (const k in store.state.axiosPromiseRecords) {
        store.state.axiosPromiseRecords[k].uid === url && store.commit('removeRepeatAxiosPromiseRecord', k)
    }
    config.cancelToken = new axios.CancelToken((cancel: any) => store.commit('addAxiosPromiseRecord', {
        uid: url,
        cancel
    }))
    // ...
    return config
}, error => Promise.reject(error))


// 响应拦截器
axios.interceptors.response.use(response => response, error => {
    if (axios.isCancel(error)) {
        console.log('路由取消请求')
        return new Promise(() => {})
    }
    return Promise.reject(error)
})

路由拦截

// ...
router.beforeEach((to, from, next) => {
    toast.clear() // 清除所有toast
    store.commit('clearAxiosPromiseRecords')
    next()
})
// ...

store

// ...
state: {
    // ...
    axiosPromiseRecords: [] // 保存接口请求记录
},
mutations: {
    // ...
    addAxiosPromiseRecord(state: any, data: any) {
        state.axiosPromiseRecords.push(data);
    },
    // 清空所有的axios请求
    clearAxiosPromiseRecords(state: any) {
        state.axiosPromiseRecords.length > 0 && state.axiosPromiseRecords.forEach((e: any) => {
            e && e.cancel()
        })
        state.axiosPromiseRecord = []
    },
    // 取消当前重复的axios请求
    removeRepeatAxiosPromiseRecord(state: any, index: number) {
        // 取消重复的请求
        state.axiosPromiseRecords[index].cancel();
        // 从axiosPromiseRecords中删除该条记录
        state.axiosPromiseRecords.splice(index, 1);
    }
}
// ...