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()  截取,設置一定時常請求一次

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM