• 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>

     效果如下:

  • 相关阅读:
    252个基本词根详解
    记忆宫殿|一个故事轻松记忆常见252个英语字根(190~252)
    海外旅游最常用的100句英语口语
    与老外见面的10大经典句
    ReportManager
    ContextLoader
    Workflow License invalid!!
    JD-GUI
    DJ Java Decompiler
    AndroChef Java Decompile
  • 原文地址:https://www.cnblogs.com/renzm0318/p/12031234.html
Copyright © 2020-2023  润新知