1、声明定时器变量
countDown: 120,
countDownTimer: null,
2、倒计时函数
// 倒计时
countDownFun() {
this.countDownTimer = setInterval(() => {
this.countDown -= 1;
if (this.countDown <= 0) {
clearInterval(this.countDownTimer);
this.countDownTimer = null;
localStorage.clear();
sessionStorage.clear();
this.$router.push('/zhuhaiHome');
}
}, 1000);
},
3、生命周期挂载倒计时方法
created() {
this.countDownFun();
},
mounted() {
// 监听全局点击事件 点击后重新计算倒计时
const that = this;
document.body.onclick = function () {
clearInterval(that.countDownTimer);
that.countDown = 120;
that.countDownFun();
};
},
4、离开页面前清除定时器
beforeDestroy() {
if (this.countDownTimer) {
clearInterval(this.countDownTimer);
this.countDownTimer = null;
}
},