微信小程序----短信验证码倒计时插件

效果图

短信验证码倒计时插件演示图

JS

// 倒计时插件
class CountTime {
  constructor(page) {
    this.page = page;
    this.time = 60;
    this.timer = null;
    this.page.setData({ code: '获取验证码', flag: false });
  }
  countTime() {
    this.page.setData({ flag: true });
    if (this.time > 0) {
      this.time--;
      this.page.setData({ code: this.time + 's后获取' });
      this.timer = setTimeout(() => {
        this.countTime();
      }, 1000);
    } else {
      this.time = 60;
      clearTimeout(this.timer);
      this.page.setData({ code: '获取验证码', flag: false });
    }
  }
}
module.exports = CountTime;

使用方法

1.引入插件countTime.js

const CountTime = require("../../utils/countTime.js");

2.在 onLoad 周期初始化

this.time = new CountTime(this);

3.在点击获取二维码按钮中使用

// 调用验证码获取倒计时方法
getCode(){
    let phoneCodeVerification = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (phoneCodeVerification.test(this.data.phone)){
        if (!this.data.flag) {
        this.time.countTime();
        // 获取验证码
        this.getCodeData();
        }else{
        this.wetoast.toast({ title: '请不要急躁,60s后再次获取!' });
        }
    }else{
        this.wetoast.toast({ title: '手机号码格式不正确,请重新输入!'});
    }
}

4.完整使用方法

const CountTime = require("../../utils/countTime.js");
const urlList = require("../../utils/config.js");
const app = getApp();
Page({
  onLoad(){
    this.time = new CountTime(this);
    // 构建WeToast
    this.wetoast = new app.WeToast();
  },
  // 获取手机号码
  getPhone(e){
    this.setData({phone: e.detail.value})
  },
  // 获取验证码
  getCodeData() {
    app.globalMethod.POST({
      url: urlList.getModifyPersonalInfoCodeUrl,
      data: { phone: this.data.phone, type: 1 },
      success: res => {
        // console.log(res)
        if (res.data.code == "200") {
          this.wetoast.toast({ title: '验证码发送成功,请注意查收!' });
        } else {
          this.wetoast.toast({ title: res.data.message });
        }
      }
    })
  },
  // 调用验证码获取倒计时方法
  getCode(){
    let phoneCodeVerification = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (phoneCodeVerification.test(this.data.phone)){
      if (!this.data.flag) {
        this.time.countTime();
        // 获取验证码
        this.getCodeData();
      }else{
        this.wetoast.toast({ title: '请不要急躁,60s后再次获取!' });
      }
    }else{
      this.wetoast.toast({ title: '手机号码格式不正确,请重新输入!'});
    }
  }
})

注意

  1. 在进行倒计时前需要对手机号进行判断,验证手机号码是否正确的正则
  2. 判断 flag 的值,防止多次点击,进行多次求情。
  3. 执行倒计时后在执行获取二维码请求的函数。

优化

  1. 按钮文字、倒计时时间、可以进行自定义使用传入值。
  2. 将倒计时不能多次点击的判断放入插件内部,调用插件直接倒计时。
  3. 防止插件没执行成功就执行了获取验证码函数,应该再建立一个插件执行的成功函数,将获取验证码的步骤放入成功函数中!

下载

我的博客,欢迎交流!

我的CSDN博客,欢迎交流!

微信小程序专栏

前端笔记专栏

微信小程序实现部分高德地图功能的DEMO下载

微信小程序实现MUI的部分效果的DEMO下载

微信小程序实现MUI的GIT项目地址

微信小程序实例列表

前端笔记列表

游戏列表

猜你喜欢

转载自blog.csdn.net/m0_38082783/article/details/80865768