上一篇文章谈到当屡次异步请求的时候,因为响应时间不可控,致使不少时候不能拿到咱们想要的正确数据,讲到用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 => { }) } } }