vue中axios防止多次觸發終止多次請求的示例程式碼(防抖)
阿新 • • 發佈:2020-02-18
需求
例如在搜尋框中,並不是你輸入一個字就需要渲染一次資料,而是取最後一次的輸入內容進行搜尋。
連續按下 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() 擷取,設定一定時常請求一次
總結
以上所述是小編給大家介紹的vue中axios防止多次觸發終止多次請求的實現方法(防抖),希望對大家有所幫助!