Vue Canvas 页面离开后返回倒计时继续更新 | 完整解决方案
当页面离开后再回来时,Vue组件的数据和状态会被重新初始化,所以倒计时不会自动更新。
为了解决这个问题,你可以使用'localStorage'或者'sessionStorage'来保存倒计时的开始时间和当前时间,在页面重新加载后再计算剩余时间。在Vue组件的'created'生命周期钩子中,可以读取这些存储的时间数据并计算剩余时间。然后将剩余时间绑定到倒计时组件的属性上,这样就能实现在页面离开后再回来时倒计时继续更新。
下面是一个简单的示例:
<template>
<div>
<h1>{{ countdown }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
countdown: 0,
startTime: null,
intervalId: null
};
},
created() {
// 读取存储的时间数据
const savedTime = localStorage.getItem('countdownStartTime');
if (savedTime) {
this.startTime = new Date(savedTime);
this.startCountdown();
}
},
methods: {
startCountdown() {
// 计算剩余时间
const currentTime = new Date();
const elapsedTime = currentTime - this.startTime;
const remainingTime = 60 - Math.floor(elapsedTime / 1000);
// 更新倒计时
this.countdown = remainingTime;
// 每秒更新一次倒计时
this.intervalId = setInterval(() => {
this.countdown--;
if (this.countdown <= 0) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}, 1000);
}
},
beforeDestroy() {
// 保存倒计时开始时间
localStorage.setItem('countdownStartTime', this.startTime);
// 清除倒计时的定时器
if (this.intervalId) {
clearInterval(this.intervalId);
}
}
};
</script>
在这个示例中,我们在'created'生命周期钩子中读取存储的开始时间,并计算剩余时间。然后在'startCountdown'方法中,我们使用'setInterval'定时器每秒更新一次倒计时,并在倒计时结束后清除定时器。在'beforeDestroy'钩子中,我们保存倒计时的开始时间,并在页面离开前清除定时器。这样就能实现在页面离开后再回来时倒计时的更新。
原文地址: https://www.cveoy.top/t/topic/qgQ3 著作权归作者所有。请勿转载和采集!