zoukankan      html  css  js  c++  java
  • vue 项目中切换页面取消接口请求

    前言: 在我们的项目中我们会遇到这种情况当我们切换页面时接口请求依旧继续,如果我们的有提示性的话语 ,在切换页面是会觉得很突兀

    第一步:

    在我们封装的axios请求里面  (我这个是移动端的H5页面的项目,用的vant ui 的框架 ,标红的部分就是我们操作的部分)

       

    import axios from 'axios';
    import Vue from "vue";
    import {Toast} from "vant";
    Vue.use(Toast)
    const service = axios.create({
    // timeout: 10000,
    headers: {
    'content-type': 'application/json'
    }
    })
    window._axiosPromiseArr = []
    service.interceptors.request.use(
    config => {
    config.cancelToken = new axios.CancelToken(cancel => {

    window._axiosPromiseArr.push({ cancel })

    })
    return config
    },
    error => {
    console.log(error)
    return Promise.reject(error)
    }
    );

    service.interceptors.response.use(
    response => {

    if (response.status === 200) {
    return response;
    } else {
    Promise.reject();
    }
    },
    error => {
    console.log(error);
    // Toast.fail('网络请求失败')
    return Promise.reject();
    }
    );

    export default service;
    第二步:在mian.js里面
    router.beforeEach((to, from, next) => {

    window._axiosPromiseArr.forEach((ele,index) => {

    ele.cancel() // 路由跳转之前,清空(终止)上一个页面正在请求的内容

    // 清空请求的参数 清空请求的参数

    delete window._axiosPromiseArr[index]
    Toast.clear(); //这个是清除我们的提示信息
    })
    next();
    })
    以上是针对与路由跳转时我们的页面情况
    当然我们也不可避免的会遇到 2个按钮切换时的接口请求
    只需要在beforeDestroy函数里面写入相应的方法即可
     //切换取消请求
    beforeDestroy() {
    window._axiosPromiseArr.forEach((ele,index) => {

    ele.cancel() // 路由跳转之前,清空(终止)上一个页面正在请求的内容

    // 清空请求的参数 清空请求的参数

    delete window._axiosPromiseArr[index]
    Toast.clear();
    })
    }
  • 相关阅读:
    编写安全有效的 C# 代码
    模式匹配
    C#新特性
    转 C# .NET4.0 混合模式程序集异常
    win7 64位系统 注册 ocx控件
    TIFF图像文件格式详解
    GDALOGR读取数据示例 C#版本
    使用gdal C#封装库读取DEM数据
    编译C#环境下GDAL(支持HDF4、NetCDF)
    UML类图符号 各种关系说明以及举例
  • 原文地址:https://www.cnblogs.com/xiebeibei/p/12396088.html
Copyright © 2011-2022 走看看