vue 写倒计时
在用vue的遇到一个问题就是一个页面里面有倒计时的时候,刷新页面会从新倒计时,为了不让计时器从新倒计时。想到了一个方法。
原理时这样的,吧获取的当前时间的,加上要倒计时的时间存到localStorage中,也就是说获取到倒计时结束的时间,存到localStorage中,在用的时候是以结束时间为基础的,废话不多说直接上代码
data() {
return {
time: '',
}
},
created() {
this.endTime();
},
methods: {
//倒计时
endTime() {
let endingTime = new Date().getTime() + 30 * 60 * 1000;
let num = localStorage.getItem("endingTime");
if (localStorage.getItem("endingTime")) {
let diff = num - new Date().getTime();
if (diff <= 0) {
localStorage.removeItem('endingTime');
} else {
let m = Math.floor(diff / 1000 / 60);
let s = Math.floor(diff / 1000 - m * 60);
this.countDown(m, s);
let s2 = s < 10 ? ('0' + s) : s;
this.time = m + '分' + s2 + '秒';
}
} else {
this.countDown(30, 0);
this.time = 29 + '分' + 60 + '秒';
localStorage.setItem("endingTime", endingTime)
}
},
//倒计时
countDown(munite, second) {
let m = munite;
let s = second;
let m2, s2;
let _this = this;
let tiem = setInterval(function () {
s--;
if (s < 0) {
s = 60;
m--;
if (m < 0) {
localStorage.removeItem('endingTime');
_this.time = '00分00秒';
clearTimeout(tiem);
return;
}
}
m2 = m < 10 ? '0' + m : m;
s2 = s < 10 ? ('0' + s) : s;
_this.time = m2 + '分' + s2 + '秒';
}, 1000)
},
}
这样就不会在页面刷新的时候从新计时了