微信小程序发送验证码倒计时,刷新页面后倒计时重新开始的问题

微信小程序发送验证码倒计时的页面,和输入手机号的页面是两个独立的页面时.

返回输入手机号页,再进入发送验证码页时,倒计时会重新开始计时.

 

可以将倒计时函数放入app.js ,在倒计时页面中定时获取全局变量中的参数,

一定要用setData将获取到的倒计时时间等数据,设置到data中,否则页面不会重新渲染.

app.js:

 1 /**
 2    * 发送验证码
 3    */
 4   dongtai:function(){
 5     var that=this;
 6     // 获取总秒数
 7     var seconds=this.globalData.max_seconds;
 8     // 显示倒计时
 9     this.globalData.send=false;
10     // 设置秒数
11     this.globalData.seconds=seconds;
12     // 设置定时器
13     var t=setInterval(function(){
14       // 如果秒数小于0
15       if(seconds<=0){
16         // 停止定时器
17         clearInterval(t);
18         // 显示发送按钮
19         that.globalData.send=true;
20         // 停止执行
21         return;
22       }
23       // 秒数减一
24       seconds--;
25       // 更新当前秒数
26       that.globalData.seconds=seconds;
27       console.log(that.globalData.seconds)
28     },1000)
29   },
30 
31 globalData: {
32 
33     // 发送验证码按钮显示
34     send:true,
35     // 当前倒计时秒数
36     seconds:"",
37     // 总秒数
38     max_seconds:59,
39   },

显示倒计时的页面:

wxml:

     <view class="dongtai_right" bindtap="dongtai" wx:if="{{send}}">
          <text>发送动态码</text>
        </view>
        <view class="dongtai_right seconds" wx:else>
          <text>{{seconds}}s</text>
        </view>

 js:

 
 1 /**
 2    * 页面的初始数据
 3    */
 4   data: {
 5     // 发送按钮显示
 6     send:app.globalData.send,
 7     // 当前倒计时秒数
 8     seconds:app.globalData.seconds,
 9     // 总秒数
10     max_seconds:app.globalData.max_seconds,
11     // 获取倒计时秒数定时器
12     time:'',
13   },
14 /**
15    * 生命周期函数--监听页面加载
16    */
17   onLoad: function (options) {
18     var that=this;
19     // 如果当前倒计时是停止状态
20     if(!app.globalData.seconds){
21       // 开始倒计时
22       app.dongtai();
23     }
24     
25   },
26 
27 /**
28    * 点击发送动态码按钮
29    */
30   dongtai:function(){
31     console.log(app)
32     // 调用倒计时
33     app.dongtai();
34     // 获取倒计时秒数
35     this.listen();
36   },
37 
38   // 监听全局倒计时秒数
39   listen:function(){
40     var that=this;
41     // 定时查询倒计时数据
42     var time=setInterval(function(){
43       that.setData({
44         // 发送按钮显示
45         send:app.globalData.send,
46         // 当前倒计时秒数
47         seconds:app.globalData.seconds,
48         // 总秒数
49         max_seconds:app.globalData.max_seconds,
50       })
51       // 倒计时结束停止定时获取
52       if(app.globalData.send){
53         clearInterval(time);
54       }
55       console.log('time')
56     },200)
57     // 存储定时器,便于清除
58     that.setData({
59       time:time,
60     })
61   },
62 
63 
64 
65 /**
66    * 生命周期函数--监听页面隐藏
67    */
68   onHide: function () {
69     // 暂停获取倒计时数据
70     clearInterval(this.data.time);
71   },
72 
73   /**
74    * 生命周期函数--监听页面卸载
75    */
76   onUnload: function () {
77     // 暂停获取倒计时数据
78     clearInterval(this.data.time);
79   },

猜你喜欢

转载自www.cnblogs.com/haoming159/p/12928515.html