zoukankan      html  css  js  c++  java
  • vue axios请求频繁时取消上一次请求

    前言

    vue axios请求频繁时取消上一次请求 连续按下 AAAAA ,只取最后一次按下时搜索框的内容(即:AAAAA)进行搜索。 而不是搜索跟 A(第一次按下),AA(第二次按下),AAA相关联的内容

    代码:

    <template>
       <input type="text" v-model="message">
    <template>
     
    <script>
    import axios from "axios";
    export default {
        data(){
            return{
                message:''
        },
        watch : {
            message(newVal){          
                var that = this;
                // 取消上一次请求
                this.cancelRequest();
                 
                axios.get('/api/searchList?cityId=10&kw='+ newVal, {             
                    cancelToken: new axios.CancelToken(function(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);
                    }
                })       
            }
        },
        methods: {
             cancelRequest(){
                if(typeof this.source ==='function'){
                    this.source('终止请求')
                }
            }
        }
     
    }
    </script>

    其他做法:

       可以使用 clearTimeout()   setTimeout()  截取,设置一定时常请求一次

     

  • 相关阅读:
    delphi try except语句 和 try finally语句用法以及区别
    正向代理与反向代理(转)
    kbmMW功能
    problem 202,263、232、21、231
    leetcode day8
    leetcode day7
    VS2013 opencv2.4.8
    web 前端routine
    leetcode day6
    leetcode day5
  • 原文地址:https://www.cnblogs.com/JonaLin/p/13664314.html
Copyright © 2011-2022 走看看