vue倒計時重新整理頁面不會從頭開始的解決方法
阿新 • • 發佈:2020-03-04
開啟倒計時,直接儲存到vuex中,且儲存到本地持久化
// state.js const runTime = localStorage.getItem('time'); paymentRunTime:runTime
// mutations.js TimeReduction(state) { this.timerId = setInterval(() => { if (state.paymentRunTime === 0) { state.paymentRunTime = 60; return clearInterval(this.timerId) } state.paymentRunTime -= 1; localStorage.setItem('time',state.paymentRunTime) },1000); },
在需要用到的頁面鉤子函式呼叫方法, created(){ this.$store.commit(TimeReduction) }
知識點擴充套件:
倒計時例項程式碼:
<template> <div class="captcha-row"> <input class="captcha-input" placeholder="輸入驗證碼" auto-focus /> <div v-if="showtime===null" class="captcha-button" @click="send"> 獲取驗證碼 </div> <div v-else class="captcha-button"> {{showtime}} </div> </div> </template>
<script> export default { data() { return { // 計時器,注意需要進行銷燬 timeCounter: null,// null 則顯示按鈕 秒數則顯示讀秒 showtime: null } },methods: { // 倒計時顯示處理 countDownText(s) { this.showtime = `${s}s後重新獲取` },// 倒計時 60秒 不需要很精準 countDown(times) { const self = this; // 時間間隔 1秒 const interval = 1000; let count = 0; self.timeCounter = setTimeout(countDownStart,interval); function countDownStart() { if (self.timeCounter == null) { return false; } count++ self.countDownText(times - count + 1); if (count > times) { clearTimeout(self.timeCounter) self.showtime = null; } else { self.timeCounter = setTimeout(countDownStart,interval) } } },send() { this.countDown(60); } },} </script>
以上就是vue倒計時重新整理頁面不會從頭開始的解決方法的詳細內容,更多關於vue倒計時重新整理頁面不會從頭開始的資料請關注我們其它相關文章!