上一篇文章談到當屢次異步請求的時候,因爲響應時間不可控,致使不少時候不能拿到咱們想要的正確數據,講到用promise all( )方法來將請求變成同步能夠解決,可是這樣就又帶來新的問題,若是請求次數過多,響應時間就會變得超長,道理很簡單,好比我在輸入框裏依次輸入‘中’,‘國’,‘建’,‘設’,‘銀’,‘行’,這樣就會向後臺發送6次請求,每次請求耗時1s, 耗時就花費了6秒,其實我只是想精確搜索「中國建設銀行」,當我最後一次改變的時候請求的數據,前面的都阻止,這樣不是就大大優化性能了嗎?結下來就引出axios 請求攔截了:javascript
export default { data(){ return{ source: null, //存放取消的請求方法 } }, methods:{ cancelQuest(){ if(typeof this.source ==='function'){ this.source('終止請求'); //取消請求 } }, getInfo(id){ const _this = this; this.cancelQuest(); //在請求發出前取消上一次未完成的請求; //發送請求 this.axios.get(`xxxxxxx`,{ cancelToken: new this.axios.CancelToken(function executor(c) { _this.source = c; }) }).then(res =>{ }).catch(error => { }) } } }