zoukankan      html  css  js  c++  java
  • uniApp定时器获取验证码

    无论是获取短信码,还是在活动页轮询获取当前活动最新信息,都需要用到定时器。 但是,定时器如果不及时合理地清除,会造成业务逻辑混乱甚至应用卡死的情况。 uni-app 中在某个页面中启动定时器后,一定要在页面关闭时将定时器清除掉。即在页面卸载(关闭)的生命周期函数里,清除定时器。

    <template>
        <view class="content">
            <button class="btn" type="primary" @click="getCode">{{ text }}</button>
        </view>
    </template>
    
    <script>
        export default {
            data() {
                return {
                    timer: null,
                    text: '获取验证码',
                    status: false,
                    num: 60
                }
            },
            methods: {
                getCode() {
                    if (this.status) {
                        return
                    }
    
                    this.status = true;
                    this.loading();
    
                    this.timer = setInterval(() => {
                        if (this.num === 0) {
                            this.timer && this.clearTimer();
                            this.reset();
                        } else {
                            this.loading();
                        }
                    }, 1000);
                },
                reset() {
                    this.num = 60;
                    this.loadingStatus = false;
                    this.text = '获取验证码';
                },
                loading() {
                    this.num -= 1;
                    this.text = '获取中(' + this.num + ')';
                },
                clearTimer() {
                    clearInterval(this.timer);
                    this.timer = null;
                }
            },
            onUnload: function() {
                this.timer && this.clearTimer();
            }
        }
    </script>
    <style>
        .content {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 750upx;
        }
    
        .btn {
            width: 400upx;
        }
    </style>

     

     测试可能有个问题,到时间清除之后,再次点击没有在计时

  • 相关阅读:
    Java 中无参带返回值方法的使用
    Java 中无参无返回值方法的使用
    如何定义 Java 中的方法
    Java 中的二维数组
    使用 foreach 操作数组
    使用 Arrays 类操作 Java 中的数组
    如何使用 Java 中的数组
    Java 循环语句之多重循环
    UML常用图的几种关系的总结
    JAVA 对象引用,以及对象赋值
  • 原文地址:https://www.cnblogs.com/li-sir/p/12964197.html
Copyright © 2011-2022 走看看