一、倒计时俩小时(刷新重新计时)
- 思路:俩小时=7200秒,将秒数转换为时分
- 代码
<template>
<span class="surplus_time">{{ count }}</span>
</template>
<script>
data(){
return{
count: "",
seconds: 7200,
}
},
mounted() {
this.Time();
},
methods: {
countDown() {
let h = parseInt((this.seconds / (60 * 60)) % 24);
h = h < 10 ? "0" + h : h;
let m = parseInt((this.seconds / 60) % 60);
m = m < 10 ? "0" + m : m;
let s = parseInt(this.seconds % 60);
s = s < 10 ? "0" + s : s;
this.count = h + ":" + m + ":" + s;
},
Time(){
this.countDown(); //解决刷新页面时,间隔一秒才会显示的问题
setInterval(()=>{
this.seconds-=1;
this.countDown()
},1000)
}
},
</script>
- 问题:刷新会重新开始倒计时
- 解决:存到sessionStorage中,如下二所示
二、倒计时俩小时(刷新不重新计时)
- 代码
<template>
<span>{{count}}</span>
</template>
<script>
data(){
return{
timme: "",
count: "",
seconds: 7200,
}
},
methods:{
dingshiqi() {
sessionStorage.setItem("examTime", this.seconds);
},
// 计时器
countDown() {
let time = sessionStorage.getItem("times");
if (time != null && time >= 0) this.seconds = parseInt(time);
let h = parseInt((this.seconds / (60 * 60)) % 24);
h = h < 10 ? "0" + h : h;
let m = parseInt((this.seconds / 60) % 60);
m = m < 10 ? "0" + m : m;
let s = parseInt(this.seconds % 60);
s = s < 10 ? "0" + s : s;
this.count = h + ":" + m + ":" + s;
},
Time() {
this.countDown();
this.timme = window.setInterval(() => {
this.seconds--;
sessionStorage.setItem("times", this.seconds);
this.countDown();
}, 1000);
},
},
mounted() {
this.Time();
},
destroyed() {
window.clearInterval(this.timme);
},
</script>
|