当前位置:首页 » 《随便一记》 » 正文

取消当前请求-vue_beichengliulixue的博客

5 人参与  2021年11月22日 16:03  分类 : 《随便一记》  评论

点击全文阅读


在某些特殊的场景业务下,需要手动停止未完成的Ajax请求,或在快速切换页面时,停止上一页面未完成的请求,减少资源浪费

实现目标:

  • 封装全局的变量及方法
  • 通过全局方法的引入,在页面直接调用该方法取消当前为完成的请求
  • 无需引入,在使用vue的页面可直接使用

实现方式

    • 新建JS文件,单独封装方法
  • 在main.js中引入该JS文件,进行全局注入 (或者直接在main.js中注入方法)
  • 在单个请求中单独添加cancelToken标识
  • 全部请求(axios封装位置)发起时添加cancelToken标识
  • 调用全局方法停止当前正在进行的Ajax请求

1、在main.js中注入方法

/**
 *取消正在进行中请求
 * cancelList设置批量取消的接口,/**代表符合该规则的全部接口
 * * 全局方法$cancelRequest可取消当前cancelList中的正在请求requset
 * * 全局方法$cancelRequest("url")可控制取消单个请求
 * */
const cancelDefaltList = ['/user/name','/org/number/**']
Vue.prototype.$currentHttpRequestList = new Map();
Vue.prototype.$cancelRequest = function(key) {
  if (key) {
    if (key.indexOf('/**') > -1) {
      Vue.prototype.$currentHttpRequestList.forEach((item, key) => {
        key.indexOf(key.split('/**')[0]) > -1 && item('Operation canceled by the user.');
      });
    } else {
      Vue.prototype.$currentHttpRequestList.get(key) && Vue.prototype.$currentHttpRequestList.get(key)('Operation canceled by the user.');
    }
  } else {
    cancelList.forEach(eachWite => {
      Vue.prototype.$currentHttpRequestList.forEach((item, key) => {
      key.indexOf(eachWite.split('/**')[0]) > -1 && item('Operation canceled by the user.')
      })
    })
 }
};

2、 在在请求拦截器中添加(也可以按照需求在某些请求中单独添加)cancelToken标识

axios.interceptors.request.use(
  function(config) {
    const CancelToken = axios.CancelToken;
    var token = getToken();
    config.headers['Content-Type'] = 'application/json; charset=UTF-8';
    config.headers.Authorization = 'bearer ' + token; // 设置请求头
    //添加cancelToken标识
    config.cancelToken = new CancelToken(function executor(c) {
      Vue.prototype.$currentHttpRequestList.set(config.url, c);
    });
    return config;
  },
  function(err) {
    if (err && err.message === 'Operation canceld by the user.') {
      console.log(err, 'errorcancel');
      return;
    }
    return Promise.reject(err);
  }
);

3、按照需求(业务逻辑)调用全局方法停止当前正在进行的Ajax请求

<template>
</template>

<script>
export default {
  name: 'test',
  data() {
    return {};
  },
  created(){
      //实际使用位置需根据具体的业务场景需求而定,此处放在created中只是个示例
      this.$cancelRequest('/user/name/**');//取消以‘/user/name/’开头的正在进行中的请求
      this.$cancelRequest('/user/age');//取消正在进行中的请求‘/user/age/’
      this.$cancelRequest();  //取消cancelDefaltList设置的全部正在进行中的请求
  },
  methods: {}

点击全文阅读


本文链接:http://zhangshiyu.com/post/31188.html

请求  方法  全局  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1