timer: 0,
jumpTime: 5,
定时器timer:0
timeChange() {
this.timer = setInterval(() => {
if (this.jumpTime) {
this.jumpTime--
} else {
this.$router.push({ path: '/' })
clearInterval(this.timer)
}
}, 1000)
},
mounted() {
this.timeChange()
},
beforeDestroy() {
clearInterval(this.timer)
},
页面加载后开始执行方法;
定义倒计时5s , 如果没有到0,继续每秒-1;
否则自动跳转到首页;并且清除定时器;
页面关闭时,清除定时器(倒计时未结束关闭页面)
demo:
<template>
<div class="about">
<h1>{{jumptime}}s</h1>
</div>
</template>
<script>
export default {
data() {
return {
jumptime: 5,
timer: 0,
};
},
mounted() {
this.changetime();
},
beforeDestory() {
clearInterval(this.timer);
},
methods: {
changetime() {
this.timer = setInterval(() => {
if (this.jumptime) {
this.jumptime--;
} else {
this.$router.push("/home");
clearInterval(this.timer);
}
}, 1000);
},
},
};
</script>