目录
  • Vue处理Axios多次请求数据显示
    • 服务端代码
    • 客户端代码
  • vue axios多次请求一个接口取消前面请求
    • 方法一
    • 方法二
  • 总结

    Vue处理Axios多次请求数据显示

    场景:

    一个搜索框,要求用户输入内容改变之后立即进行搜索

    遇到的问题:

    用户频繁的进行搜索词修改,会触发很多次搜索请求,如果请求有延时,就会出现显示不正确的现象

    比如下面这个例子:

    • 请求1发出后,存在延时大,响应1后返回;
    • 请求2发出后,延时小,响应2先返回;
    • 最后显示的内容是响应1;

    而我期待的显示内容,是最后一次的请求结果响应2

    请求1 ——-> 延时 ———> 响应1
         请求2 -> 延时 -> 响应2

    服务端代码

    server.py

    # -*- coding: utf-8 -*-
    
    from flask import Flask, request
    from flask_cors import CORS
    import time
    import random
    
    app = Flask(__name__)
    
    # 允许跨域
    CORS(app, supports_credentials=True)
    
    # 路由
    @app.route('/search')
    def search():
        # 模拟网络延时
        sleep = random.random() * 2
        
        time.sleep(sleep)
    
        keyword = request.args.get('keyword')
    
        return {'keyword': keyword, "sleep": sleep}
    
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    客户端代码

    1、直接请求,会出现数据显示不对的情况

    <template>
      <div class="">
        <input
          type="text"
          @input="handleInput"
        >{{result}}</div>
    </template>
    
    <script>
    import axios from 'axios';
    
    export default {
      name: '',
    
      data() {
        return {
          result: '',
        };
      },
    
      methods: {
        async handleInput(e) {
          const keyword = e.target.value;
    
          const res = await this.search(keyword);
          this.result = res.data;
        },
    
        // 直接搜索:可能显示的不是最后一次搜索结果
        async search(keyword) {
          return await axios.get('http://127.0.0.1:5000/search', {
            params: { keyword: keyword },
          });
        },
    
      },
    };
    </script>
    
    <style lang="scss" scoped>
    </style>

    2、增加一个定时器

    import axios from 'axios';
    
    export default {
      name: '',
    
      data() {
        return {
          result: '',
          timer: null, // 定时器
        };
      },
    
      methods: {
        async handleInput(e) {
          
          const keyword = e.target.value;
    
          const res = await this.searchForTimeout(keyword);
    
          this.result = res.data;
          
        },
    
        // 加定时器:会有一个延迟,如果有超过500ms的网络延时,也会出现数据不一致
        async searchForTimeout(keyword) {
          return new Promise((resolve, reject) => {
            // 清除没执行的timer定时器
            clearTimeout(this.timer);
    
            this.timer = setTimeout(() => {
              try {
                const res = axios.get('http://127.0.0.1:5000/search', {
                  params: { keyword: keyword },
                });
                resolve(res);
              } catch (e) {
                reject(e);
              }
            }, 500);
          });
        },
      }
    };

    3、加请求时间戳

    import axios from 'axios';
    
    // 使用axios的拦截器
    const instance = axios.create();
    
    instance.interceptors.request.use(
      (config) => {
        config['X-Timestamp'] = new Date().getTime();
        return config;
      },
      (err) => {
        return Promise.reject(err);
      }
    );
    
    instance.interceptors.response.use(
      (res) => {
        res.data.timestamp = res.config['X-Timestamp'];
        return res;
      },
      (err) => {
        return Promise.reject(err);
      }
    );
    
    export default {
      name: '',
    
    
      data() {
        return {
          result: '',
          timestamp: 0, // 相当于版本号
        };
      },
    
      methods: {
        async handleInput(e) {
          const keyword = e.target.value;
    
          const res = await this.searchForTimestamp(keyword);
    
          // 如果时间戳大于当前记录的时间戳则更新数据
          if (res.data.timestamp > this.timestamp) {
            this.timestamp = res.data.timestamp;
            this.result = res.data;
          }
        },
    
        // 加请求时间戳:类似乐观锁
        async searchForTimestamp(keyword) {
          return instance.get('http://127.0.0.1:5000/search', {
            params: { keyword: keyword },
          });
        },
      },
    };

    vue axios多次请求一个接口取消前面请求

    方法一

        var CancelToken = axios.CancelToken;
        var source = CancelToken.source(); // 每次调用接口之前都赋值一下 不然不会触发请求
        axios.get('/user/12345', {//get请求在第二个参数
         cancelToken: source.token
        }).catch(function(thrown) {
        });
        axios.post('/user/12345', {//post请求在第三个参数
         name: 'new name'
        }, {
         cancelToken: source.token
        });
        source.cancel('不想请求了');

    方法二

    const CancelToken = axios.CancelToken;
    let cancel;
     
    axios.get('/user/12345', {
      cancelToken: new CancelToken(function executor(c) {
        // executor 函数接收一个 cancel 函数作为参数
        cancel = c;
      })
    });
     
    // cancel the request
    cancel();

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。