• vue axios请求频繁时取消上一次请求


    vue axios请求频繁时取消上一次请求

     

    一、前言

    在项目中经常有一些场景会连续发送多个请求,而异步会导致最后得到的结果不是我们想要的,并且对性能也有非常大的影响。例如一个搜索框,每输入一个字符都要发送一次请求,但输入过快的时候其实前面的请求并没有必要真的发送出去,这时候就需要在发送新请求的时候直接取消上一次请求。

    二、代码

    <script>
    import axios from 'axios'
    import qs from 'qs'
    
    export default {
        methods: {
            request(keyword) {
                var that = this;
                var CancelToken = axios.CancelToken
                var source = CancelToken.source()
                  
                // 取消上一次请求
                this.cancelRequest();
                
                axios.post(url, qs.stringify({kw:keyword}), {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Accept': 'application/json'
                    },
                    cancelToken: new axios.CancelToken(function executor(c) {
                        that.source = c;
                    })
                }).then((res) => {
                    // 在这里处理得到的数据
                    ...
                }).catch((err) => {
                    if (axios.isCancel(err)) {
                        console.log('Rquest canceled', err.message); //请求如果被取消,这里是返回取消的message
                    } else {
                        //handle error
                        console.log(err);
                    }
                })
            },
            cancelRequest(){
                if(typeof this.source ==='function'){
                    this.source('终止请求')
                }
            },
        }
    }
    </script>

    三、结语

    这样就可以成功取消上一次请求啦!真的非常好用~

    转载于:https://segmentfault.com/a/1190000016963943

  • 相关阅读:
    Best code水题之路
    我的CodeF水A题之路
    studing(来自转载)
    BFS
    fibonacci数列(五种)
    Redis阻塞队列原理学习
    the enum hack
    Divide Two Integers
    Surrounded Regions
    Search in Rotated Sorted Array
  • 原文地址:https://www.cnblogs.com/lin137/p/13266893.html
Copyright © 2020-2023  润新知