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

     

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

  • 相关阅读:
    策略模式(Strategy Pattern)
    责任链模式(Chain of Responsibility Pattern)
    单例模式(Singleton Pattern)
    观察者模式(Observer Pattern)
    iOS常用工具类
    iOS常用的封装方法
    iOS中书写代码规范
    UITableViewCell中的使用cell和cell.contentView的区别
    colorWithAlphaComponent
    iOS 压缩图片
  • 原文地址:https://www.cnblogs.com/li-sir/p/12964197.html
Copyright © 2020-2023  润新知