1. 程式人生 > >微信小程式-簡訊驗證碼

微信小程式-簡訊驗證碼

// pages/info-two/info-two.jsPage({
/** * 頁面的初始資料 */ data: { send: false, alreadySend: false, second: 60, disabled: true, buttonType: 'default', phoneNum: '', code: '', },

// 手機號部分 inputPhoneNum: function (e) { let phoneNum = e.detail.value if (phoneNum.length === 11) { let
checkedNum = this.checkPhoneNum(phoneNum) if (checkedNum) { this.setData({ phoneNum: phoneNum }) console.log('phoneNum=' + this.data.phoneNum) this.showSendMsg() this.activeButton() } } else { this.setData({ phoneNum: '' }) this
.hideSendMsg() } },
checkPhoneNum: function (phoneNum) { let str = /^1\d{10}$/ if (str.test(phoneNum)) { return true } else { wx.showToast({ title: '手機號不正確', icon: 'none' }) return false } },
showSendMsg: function () { if (!this.data.alreadySend) { this
.setData({ send: true }) } },
hideSendMsg: function () { this.setData({ send: false, disabled: true, buttonType: 'default' }) },
sendMsg: function () { console.log('傳送獲取驗證碼') this.setData({ alreadySend: true, send: false }) // this.timer() this.countdown() },
timer: function () { //Promise:ES6將其寫進了語言標準 獲取非同步操作的訊息 let promise = new Promise((resolve, reject) => { let setTimer = setInterval( () => { this.setData({ second: this.data.second - 1 }) if (this.data.second <= 0) { this.setData({ second: 60, alreadySend: false, send: true }) // resolve非同步操作成功 resolve(setTimer) } } , 1000) }) // 將Promise物件的狀態從“未完成”變為“成功” promise.then((setTimer) => { console.log('resolve非同步操作成功') clearInterval(setTimer) }) },
countdown:function() { var that=this var second=this.data.second if(second==0) { that.setData({ second: 60 }) return } var time=setTimeout(function(){ that.setData({ second: second-1 }) that.countdown(that) },1000) },
// 驗證碼 addCode: function (e) { console.log('驗證碼-addCode') this.setData({ code: e.detail.value }) this.activeButton() },
// 按鈕 activeButton: function () { //let{} es6的解構賦值。大括號中的key對應item的key 其值也是相對應的 let { phoneNum, code } = this.data console.log(this.data) if (phoneNum) { this.setData({ disabled: false, buttonType: 'primary' }) } else { this.setData({ disabled: true, buttonType: 'default' }) } }, // 提交 onSubmit: function () { console.log('onSubmit') //模擬校驗驗證碼 if(this.data.code=='123456'){ wx.showToast({ title: '驗證成功', icon:'success' }) }else { wx.showToast({ title: '驗證失敗', icon: 'none' }) } },
/** * 生命週期函式--監聽頁面載入 */ onLoad: function (options) {
},
/** * 生命週期函式--監聽頁面初次渲染完成 */ onReady: function () {
},
/** * 生命週期函式--監聽頁面顯示 */ onShow: function () {
},
/** * 生命週期函式--監聽頁面隱藏 */ onHide: function () {
},
/** * 生命週期函式--監聽頁面解除安裝 */ onUnload: function () {
},
/** * 頁面相關事件處理函式--監聽使用者下拉動作 */ onPullDownRefresh: function () {
},
/** * 頁面上拉觸底事件的處理函式 */ onReachBottom: function () {
},
/** * 使用者點選右上角分享 */ onShareAppMessage: function () {
}})