微信小程序----短信驗證碼倒計時插件

效果圖

短信驗證碼倒計時插件演示圖

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項目地址

微信小程序實例列表

前端筆記列表

遊戲列表

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章