第一種,簡單時長倒計時
data() { return { timer: null, m: 0, s: 0, time: null, } }, created() { this.resetTime(125); //倒計時125S,根據自己的時長確定 }, methods: { //單純分鍾和秒倒計時 resetTime(time){ this.m = Math.floor(time / 60); this.m = this.m < 10 ? `0${this.m}` : this.m; console.log('this.m--',this.m); this.s = Math.floor(time % 60); this.timer = setInterval(this.countDown,1000); }, countDown(){ this.s--; this.s < 10 && (this.s = '0' + this.s); // this.s = this.s < 10 ? `0${this.s}` : this.s; if(this.s.length >= 3){ this.s = 59; this.m = `0${(Number(this.m)-1)}`; } if(this.m.length >= 3){ this.m='00'; this.s='00'; clearInterval(this.timer); } this.time = `${this.m}分鍾${this.s}秒`; console.log(this.m+"分鍾"+this.s+"秒"); }, }
第二種,根據后端返回的時間戳,與當前時間進去比較,進行倒計時
data() { return {
timer: null,
time: null, } }, created() {
this.timer = setInterval(this.countTime,1000);
}, methods: { countTime() { //獲取當前時間 let date = new Date(); let now = date.getTime(); //設置截止時間 let str="2021/3/15 00:00:00"; let endDate = new Date(str); let end = endDate.getTime(); //時間差 let leftTime = end - now; //定義變量 d,h,m,s保存倒計時的時間 let d,h,m,s; if (leftTime >= 0) { d = Math.floor(leftTime/1000/60/60/24); h = Math.floor(leftTime/1000/60/60%24); m = Math.floor(leftTime/1000/60%60); s = Math.floor(leftTime/1000%60); }else {
clearInterval(this.timer); //為負數時清掉定時器
}
//遞歸每秒調用countTime方法,顯示動態時間效果 this.time = `${m}分${s}秒`;
if(m == 0 && s == 0) {
clearInterval(this.timer); //時間倒計完清掉計時器,並且跳轉,這里根據自己的需求寫就好了
this.$app.$redirect('/register/invallid',true);
}
},
}
參照: https://www.cnblogs.com/heizai002/p/6862418.html