<template>
<div id="app">
<span>{{ totalTime }}</span>
</div>
</template>
<script>
export default {
data() {
return {
// 60秒倒计时
totalTime: 60,
canClick: true,
// 计时器
clock: '',
};
},
activated: function () {
// 调用倒计时方法
this.countDown();
},
beforeDestroy() {
if (this.clock) {
// 销毁计时器
clearInterval(this.clock);
}
},
methods: {
// 每题倒计时
countDown() {
clearInterval(this.clock);
if (!this.canClick) {
return;
}
this.canClick = false;
this.clock = window.setInterval(() => {
this.totalTime--;
if (this.totalTime === 10) {
this.showWarning();
}
if (this.totalTime < 0) {
clearInterval(this.clock);
this.totalTime = 60;
this.canClick = true;
// 下一题
this.next();
}
}, 1000);
},
showWarning() {
this.$message({
duration: 2000,
message: "10秒后自动跳转下一题",
type: "warning",
});
},
// 下一题
next() {
...
this.countDown();
},
},
};
</script>