欢迎来到代码驿站!

vue

当前位置:首页 > 网页前端 > vue

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

时间:2021-02-17 14:07:16|栏目:vue|点击:

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

<!-- 考试倒计时组件 -->
<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

下一篇:Vue开发之watch监听数组、对象、变量操作分析

本文标题:Vue 封装防刷新考试倒计时组件的实现

本文地址:http://www.codeinn.net/misctech/64977.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有