美文网首页
vue 取消请求(抢单案例)

vue 取消请求(抢单案例)

作者: mutang | 来源:发表于2021-02-17 13:10 被阅读0次

    说明:

    在抢单案例中,第一次发送,为正常发送,在请求结果返回之前再次发送请求,则取消掉;

    测试环境:

    • json-server
      json-server --watch db.json -d 2000
    

    json-server延迟两秒

    • axios

    代码:

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
    </head>
    <body>
    <button type="button" class="btn btn-success">发送get</button>
    
    <button type="button" class="btn btn-primary">发送post</button>
    
    <button type="button" class="btn btn-info">(一般信息)Info</button>
    <script>
        
        let btns = document.querySelectorAll('button');
        // 声明全局变量
        let cancel = null;
        //get
        // 发送请求
        btns[0].onclick = function () {
            // 检测上一次请求是否完成
            if(cancel != null){
                cancel();
            }
            axios.request({
                url: 'http://localhost:3000/posts',
                // 添加配置对象的属性
                cancelToken: new axios.CancelToken(
                    // 将c赋值给cancel
                    c => cancel = c
                )
            }).then(
                res => {
                    console.log(res);
                    // 将cancel的值初始化
                    cancel = null
                }
            )
        };
    
    </script>
    </body>
    </html>
    

    结果:

    连续发送,不会成功

    相关文章

      网友评论

          本文标题:vue 取消请求(抢单案例)

          本文链接:https://www.haomeiwen.com/subject/jbpixltx.html