zoukankan      html  css  js  c++  java
  • vue axios路由跳转取消所有请求 和 防止重复请求

    直接上干货

    在发送第二次请求的时候如果第一次请求还未返回,则取消第一次请求,以保证后发送的请求返回的数据不会被先发送的请求覆盖。

    或者是跳转路由的时候取消还未返回的请求

    第一步: axios 怎么取消:

    const CancelToken = axios.CancelToken;
    let cancel;
    axios.get('/user/12345', {
    cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
    })
    });

    第二步: 这是取消一个axios 如果是多个呢?那么我们就需要有个地方给存下来
    vuex
    state: {
    // axios取消请求
    axiosPromiseCancel: [],
    }
    第三步: axios 拦截器axios.js
    import store from './store';
    const CancelToken = axios.CancelToken;

    let cancel;
    // 防止重复请求
    let removePending = (config) => {
    for (let k in store.state['axiosPromiseCancel']) {
    if (store.state['axiosPromiseCancel'][k].u === config.url + '&' + config.method) { //当前请求在数组中存在时执行函数体
    store.state['axiosPromiseCancel'][k].f(); //执行取消操作
    store.state['axiosPromiseCancel'].splice(k, 1); //把这条记录从数组中移除
    }
    }
    };
    axios.interceptors.request.use(config=>{
    // 这个是 取消重点
    removePending(config);
    config.cancelToken = new CancelToken((cancel) => {
    store.state['axiosPromiseCancel'].push({ u: config.url + '&' + config.method, f: cancel });
    });
      return config;
    });
    axios.interceptors.response.use(res=>{
    removePending(res.config);
      // do something...
    },error=>{
    if (axios.isCancel(error)) {
    // 为了终结promise链 就是实际请求 不会走到.catch(rej=>{});这样就不会触发错误提示之类了。
    return new Promise(() => {});
    }else{
    return Promise.reject(error)
    }});

    第四步: 就是在router 里做取消动作了 router.js

    import store from './store';
    router.beforeEach((to, from, next) => {
    if(store.state['axiosPromiseCancel'].length > 0) {
    store.state['axiosPromiseCancel'].forEach(e => {
    e && e.f()
    });
    }
    store.state['axiosPromiseCancel'] = [];

    })
  • 相关阅读:
    响应报文
    IntelliJ IDEA 使用Git怎样记住密码和忘记密码的方法
    vue基础——命名路由
    vue基础——路由懒加载
    vue hash模式下如何使用a标签的锚点定位
    vue项目中修改第三方库的组件样式的方法
    CSS3实现水波纹效果
    日期对象Date的计算
    兼容性查询工具
    根据.svg文件借助IconMoon生成字体图标及应用的方法
  • 原文地址:https://www.cnblogs.com/zhaofeis/p/11422777.html
Copyright © 2011-2022 走看看