vue.js—60秒倒計時
最近專案中需要實現獲取驗證碼的功能,這裡做了一個簡單實現方式。
廢話不多說,直接擼程式碼。。。。。
<div class="purse-mid-yanzheng">
<span class="purse-mid-yanzheng-one">驗證碼</span>
<input type="text" placeholder="請輸入驗證碼" />
<span class="purse-mid-yanzheng-two" @click="sendVcode(mobile)" id="yzm">獲取驗證碼</span>
</div>
js:
export default {
data: function() {
return {
times: "60", //60秒倒計時
}
},
methods: {
//傳送驗證碼,校驗手機號
sendVcode: function(moblie) {
alert(moblie);
var that = this;
var regMoblie = /^1[345678]\d{9}$/;
if(!regMoblie.test(moblie)) {
msg('該手機號格式錯誤');
return;
}
$.ajax({
type: "post",
url: "/send_verification_code.do",
async: true,
data: {
mobile: moblie
},
dataType: "json",
success: function(result) {
if(result.result_code == 0) {
msg("獲取驗證碼成功,請注意簡訊查收!");
that.countdown();
} else {
msg("獲取驗證碼失敗!");
console.log("獲取驗證碼失敗");
}
},
error: function() {
msg("伺服器發生異常,請稍後再試!");
}
});
},
//60秒倒計時
countdown: function() {
var that = this;
if(that.times == 0) {
$('#yzm').html("獲取驗證碼");
that.times = 60;
return false;
} else {
$('#yzm').html("" + that.times + "s");
that.times--;
}
setTimeout(function() {
that.countdown();
}, 1000);
},
},
mounted: function() {
}
};
ps: setInterval 實現倒計時,並清除計時器 //週期執行
需求:60s倒計時,自動執行agree();函式,也可以點選執行,返回時要清除計時器
export default {
data: function() {
return {
time: 60,
interval: ""
}
},
methods: {
goback: function() {
clearInterval(this.interval); //清除計時器
window.history.go(-1);
},
countdown: function() {
let that = this;
let interval = window.setInterval(function() {
that.interval = interval;
if ((that.time--) <= 1) {
clearInterval(interval);
that.agree(); //執行函式
}
}, 1000);
}
},
mounted: function() {
this.countdown(); //網頁載入完成時呼叫
}
};,