vue 发送请求频繁时取消上一次请求

前言:

  在项目中经常有一些场景会连续发送多个请求,而异步会导致最后得到展示的结果可能不是最后一次发送请求返回的结果,且对性能也有非常大的影响。

场景:

  列表式切换商品,有时候上一次请求的结果非常慢,而我又点了另外一个商品,这时候第二次请求的接口比上一次快,那么就点击第二次的商品看到的信息却是上一次的商品信息,这样的用户体验极其不好;

解决方案:

  在点击下一个商品的时候,将上一个商品请求的接口中断取消请求。

代码如下:

<script>
import axios from 'axios'

export default { data() { return { source: null, } }, methods: { cancelRequest() { if (typeof this.source === 'function') { this.source() } }, getProductPackageInfo() { const _this = this; this.cancelRequest(); // 取消上一次请求 axios({ method: 'post', url: this.secondURL.getProductPackageInfo, data: { name: '小白' }, cancelToken: new axios.CancelToken((c) => { _this.source = c }), }) .then((res) => { // 返回数据进行操作 }).catch((err) => {if (axios.isCancel(err)) { console.log('Rquest canceled', err.message); //请求如果被取消,这里是返回取消的message } else { console.log(err); } }) }, </script>

 效果如下:

 

 

posted @ 2019-12-12 19:46  灰姑娘的冰眸  阅读(3502)  评论(0编辑  收藏  举报