首页前端开发VUEVue如何处理Axios多次请求数据显示问题

Vue如何处理Axios多次请求数据显示问题

时间2024-02-11 05:55:03发布访客分类VUE浏览173
导读:收集整理的这篇文章主要介绍了Vue如何处理Axios多次请求数据显示问题,觉得挺不错的,现在分享给大家,也给大家做个参考。 目录Vue处理Axios多次请求数据显示服务端代码客户端代码v...
收集整理的这篇文章主要介绍了Vue如何处理Axios多次请求数据显示问题,觉得挺不错的,现在分享给大家,也给大家做个参考。
目录
  • 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, requestfrom flask_cors import CORSimport timeimport randomapp = 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('不想请求了');
        

    @L_304_12@

    方法二

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

    总结

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

    您可能感兴趣的文章:
    • Vue之Axios的异步请求问题详解
    • vue axios接口请求封装方式
    • Vue使用axios进行get请求拼接参数的2种方式详解
    • vue中使用axios固定url请求前缀
    • Vue简单封装axios网络请求的方法
    • Vue使用ajax(axios)请求后台数据的方法教程
    • Vue axios库避免重复发送请求的示例介绍

    声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


    若转载请注明出处: Vue如何处理Axios多次请求数据显示问题
    本文地址: https://pptw.com/jishu/609406.html
    vue的axios使用post时必须使用qs.stringify而get不用问题 Vue3之Vite中由element ui更新导致的启动报错解决

    游客 回复需填写必要信息