在做微信小程序時,需要發送短信驗證碼60S倒計時,下面我就寫一下我自己的方法

WXML按鈕
<button hidden="{{nullHouse1}}" class="get_code" bindtap="getcode" data-mess="{{sms_zt}}" >{{sms_zt}} </button>
<button hidden="{{nullHouse2}}" class="get_code">{{second}}s后重新獲取</button>
JS
// pages/login/login.js
Page({
/**
* 頁面的初始數據
*/
data: {
sms_zt : '發送驗證碼',
message:'請輸入您的手機號碼',
second: 60,
nullHouse1: false,
nullHouse2:true
},
/**
* 生命周期函數--監聽頁面加載
*/
onLoad: function (options) {
var that = this
wx.setNavigationBarTitle({
title: '綁定手機'
})
//獲取用戶信息
wx.getStorage({
key: 'user',
success: function (res) {
console.log(res.data)
that.setData({
user:res.data
})
}
})
},
getcode: function (e) {
var phone = this.data.phone
if(!phone){
var that = this;
this.setData({
nullHouse: false, //彈窗顯示
})
setTimeout(function () {
that.setData({
nullHouse: true //彈窗顯示
})
}, 2000)
}else{
var that = this
wx.request({
url: getApp().data.web_url + '/index.php?s=/Index/api/get_sms', //獲取短信驗證碼
data: {
phone: phone
},
header: {
"Content-Type": "application/json"
},
success: function (res) {
console.log(res.data)
if(res.data.state == 1){
countdown(that)
}
}
})
}
}
})
//倒計時方法
function countdown(that) {
var second = that.data.second;
if (second == 0) {
// console.log("Time Out...");
that.setData({
selected: false,
selected1: true,
second: 60,
nullHouse1: false,
nullHouse2: true
});
return;
}
var time = setTimeout(function () {
that.setData({
second: second - 1,
nullHouse1: true,
nullHouse2: false
});
countdown(that);
}, 1000)
}
