Vue回炉重造之封装防刷新考试倒计时组件

怼烎@ 2021-08-27 16:14 528阅读 0赞

你好,我是Vam的金豆之路,可以叫我豆哥。2019年年度博客之星、技术领域博客专家。主要领域:前端开发。我的微信是 maomin9761,有什么疑问可以加我哦,自己创建了一个微信技术交流群,可以加我邀请你一起交流学习。最后自己也创建了一个微信公众号:前端历劫之路,欢迎关注。


欢迎阅读本博文,本博文主要讲述【Vue回炉重造之封装防刷新考试倒计时组件】,文字通俗易懂,如有不妥,还请多多指正。

在这里插入图片描述

  1. <!-- 考试倒计时组件 -->
  2. <template>
  3. <div class="time">
  4. <p>00:{
  5. {timerCount2}}:{
  6. {timerCount1}}</p>
  7. <button @click="reset">重新计时</button>
  8. </div>
  9. </template>
  10. <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>
  11. <style scoped> .time { color: #f72a3a; font-weight: bold; font-size: 26px; } </style>

谢谢阅读,如果觉得有感触,麻烦帮忙点个赞,关个注吧!

发表评论

表情:
评论列表 (有 0 条评论,528人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Gitee回炉

    使用Gitee两个目的 1. 自己创建仓库,将本地项目上传到码云(gitee)远程仓库 2. 在别人的开源项目基础上修改 自己创建仓库,将本地项目上传到码云(gi