需求
例如在搜索框中,并不是你輸入一個(gè)字就需要渲染一次數(shù)據(jù),而是取最后一次的輸入內(nèi)容進(jìn)行搜索。
連續(xù)按下 AAAAA ,只取最后一次按下時(shí)搜索框的內(nèi)容(即:AAAAA)進(jìn)行搜索。 而不是搜索跟 A(第一次按下),AA(第二次按下),AAA相關(guān)聯(lián)的內(nèi)容
本文例子: 檢測(cè)用戶輸入的值,監(jiān)測(cè)這個(gè)值,然后根據(jù)值調(diào)用接口查詢結(jié)果
代碼:
<template> <input type="text" v-model="message"><template><script>import axios from "axios";export default { data(){ return{ message:'' }, watch : { message(newVal){ var that = this; // 取消上一次請(qǐng)求 this.cancelRequest(); axios.get('/api/searchList?cityId=10&kw='+ newVal, { cancelToken: new axios.CancelToken(function(c) { that.source = c; }) }).then((res) => { // 在這里處理得到的數(shù)據(jù) //數(shù)據(jù)邏輯處理 }).catch((err) => { if (axios.isCancel(err)) { console.log('Rquest canceled', err.message); //請(qǐng)求如果被取消,這里是返回取消的message } else { //handle error console.log(err); } }) } }, methods: { cancelRequest(){ if(typeof this.source ==='function'){ this.source('終止請(qǐng)求') } } }}</script>其他做法:
可以使用 clearTimeout() setTimeout() 截取,設(shè)置一定時(shí)常請(qǐng)求一次
總結(jié)
以上所述是小編給大家介紹的vue中axios防止多次觸發(fā)終止多次請(qǐng)求的實(shí)現(xiàn)方法(防抖),希望對(duì)大家有所幫助!
新聞熱點(diǎn)
疑難解答
圖片精選