1. 程式人生 > >微信小程式----簡訊驗證碼倒計時外掛

微信小程式----簡訊驗證碼倒計時外掛

效果圖

簡訊驗證碼倒計時外掛演示圖

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. 判斷 flag 的值,防止多次點選,進行多次求情。
  2. 執行倒計時後在執行獲取二維碼請求的函式。

優化

  1. 按鈕文字、倒計時時間、可以進行自定義使用傳入值。
  2. 將倒計時不能多次點選的判斷放入外掛內部,呼叫外掛直接倒計時。
  3. 防止外掛沒執行成功就執行了獲取驗證碼函式,應該再建立一個外掛執行的成功函式,將獲取驗證碼的步驟放入成功函式中!

下載

遊戲列表