Vue 封装防刷新考试倒计时组件的实现

时间:2021-05-26

本文详细的介绍了防刷新考试倒计时组件 ,分享给大家,也给自己留个笔记,感兴趣的可以了解下

<!-- 考试倒计时组件 --><template> <div class="time"> <p>00:{{timerCount2}}:{{timerCount1}}</p> <button @click="reset">重新计时</button> </div></template><script>export default { name: "Time", data() { return { timeSeconds: 0, timeMinutes: 0, seconds: 59, // 秒 minutes: 1, // 分 timer: null }; }, methods: { num(n) { return n < 10 ? "0" + n : "" + n; }, // 重新计时 reset() { sessionStorage.removeItem("answered"); window.location.reload(); localStorage.removeItem("startTime1"); localStorage.removeItem("startTime2"); clearInterval(this.timer); }, // 清除 clear() { localStorage.removeItem("startTime1"); localStorage.removeItem("startTime2"); sessionStorage.setItem("answered", 1); clearInterval(this.timer); }, // 倒计时 timing() { let [startTime1, startTime2] = [ localStorage.getItem("startTime1"), localStorage.getItem("startTime2") ]; let nowTime = new Date().getTime(); if (startTime1) { let surplus = this.seconds - parseInt((nowTime - startTime1) / 1000); this.timeSeconds = surplus <= 0 ? 0 : surplus; } else { this.timeSeconds = this.seconds; localStorage.setItem("startTime1", nowTime); //存储秒 } if (startTime2) { this.timeMinutes = startTime2; } else { this.timeMinutes = this.minutes; localStorage.setItem("startTime2", this.minutes); //存储分 } this.timer = setInterval(() => { if ( this.timeSeconds == 0 && this.timeMinutes != 0 && this.timeMinutes > 0 ) { let nowTime = new Date().getTime(); this.timeSeconds = this.seconds; localStorage.setItem("startTime1", nowTime); this.timeMinutes--; localStorage.setItem("startTime2", this.timeMinutes); } else if (this.timeMinutes == 0 && this.timeSeconds == 0) { this.timeSeconds = 0; this.clear(); alert("考试时间到"); } else { this.timeSeconds--; } }, 1000); } }, mounted() { if (sessionStorage.getItem("answered") != 1) { this.timing(); } }, computed: { timerCount1() { return this.timeSeconds < 10 ? "0" + this.timeSeconds : "" + this.timeSeconds; }, timerCount2() { return this.timeMinutes < 10 ? "0" + this.timeMinutes : "" + this.timeMinutes; } }, destroyed() { // 退出后清除计时器 if (this.timer) { clearInterval(this.timer); } }};</script><style scoped>.time { color: #f72a3a; font-weight: bold; font-size: 26px;}</style>

到此这篇关于Vue 封装防刷新考试倒计时组件的实现的文章就介绍到这了,更多相关Vue 防刷新考试倒计时组件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章