Vue中用JSON實現(xiàn)刷新界面不影響倒計時
本文實例為大家分享了Vue中用JSON實現(xiàn)刷新界面不影響倒計時的具體代碼,供大家參考,具體內(nèi)容如下
效果展示:
部分代碼
<el-form-item v-if='env === ’dev’'> <el-input v-model='ruleForm.nucCode' size='small' placeholder='請輸入短信驗證碼' /> <el-button @click='getNumCode'> <span v-if='isShowNucTime' >{{Nuc_time}} S</span> <span v-else-if='!isShowNucTime && NucAgain' >重新獲取驗證碼</span> <span v-else >獲取短信驗證碼</span> </el-button></el-form-item>
isShowNucTime:boolean = false;NucAgain: boolean = false;Nuc_code_freash: boolean = false; // 判斷驗證碼是否過期Nuc_time: number = 60;end_time: number = 0;private getCode() { let clicktime = new Date().getTime() + 60000; // 本地存儲 localStorage.setItem(’myEndTime’, JSON.stringify(clicktime)); this.timeDown(clicktime); } // 驗證碼倒計時 timeDown(counttime: any) { // 判斷是否正在倒計時 if (this.isShowNucTime) return; this.userChange = false; this.isShowNucTime = true; this.isGetNucCode = true; this.end_time = Number(localStorage.getItem(’myEndTime’)); this.Nuc_time = Math.ceil((this.end_time - new Date().getTime()) / 1000); let interval = setInterval(() => { this.Nuc_time--; if (this.Nuc_time < 1) { this.Nuc_time = 60; this.isShowNucTime = false; localStorage.removeItem(’myEndTime’); if (!this.userChange) { this.NucAgain = true; } clearInterval(interval); } }, 1000) }private created(): void { let myEndTime= localStorage.getItem(’myEndTime’); myEndTime && this.timeDown(myEndTime); }
重要的代碼部分
實現(xiàn)原理
1.首次加載頁面 點擊開始
1).獲取當(dāng)前時間戳與要倒計時的時間相加獲得要停止計時的時間
2).用localStorage保存當(dāng)前時間戳
3).通過js的setInterval定時器進(jìn)行倒計時
4).當(dāng)?shù)褂嫊r結(jié)束后 清除localStorage中保存的結(jié)束時間
2.當(dāng)?shù)趎次進(jìn)入頁面或刷新頁面時
1).首先判斷l(xiāng)ocalStorage中倒計時是否結(jié)束
2).沒有結(jié)束則繼續(xù)倒計時
3).如果結(jié)束則顯示重新發(fā)送驗證碼
主要運用了localStorage + new Date().getTime() PS:本文只是展示部分代碼,一味的復(fù)制粘貼并不能運行,還是搞清楚邏輯自己實現(xiàn)比較靠譜!關(guān)于vue.js組件的教程,請大家點擊專題vue.js組件學(xué)習(xí)教程進(jìn)行學(xué)習(xí)。
更多vue學(xué)習(xí)教程請閱讀專題《vue實戰(zhàn)教程》
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
