Vue 封装防刷新考试倒计时组件的实现
程序员文章站
2022-04-09 16:13:03
本文详细的介绍了防刷新考试倒计时组件 ,分享给大家,也给自己留个笔记,感兴趣的可以了解下
本文详细的介绍了防刷新考试倒计时组件 ,分享给大家,也给自己留个笔记,感兴趣的可以了解下
<!-- 考试倒计时组件 --> <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 防刷新考试倒计时组件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!