HTML
<template>
<div @click="countdowm" v-text="content "></div>
</template>
在data里边定义相关变量
data() {
return {
content: "倒计时",
canClick: true,
refreshData: null
};
},
在methods里边定义相关方法
methods: {
countdowm() {
let totalTime = 60;
if (!this.canClick) return; //节流
this.canClick = false;
this.content = totalTime + "s后重新倒计时";
this.refreshData = window.setInterval(() => {
totalTime--;
this.content = totalTime + "s后重新倒计时";
if (totalTime < 0) {
//当倒计时小于0时清除定时器
window.clearInterval(this.refreshData); //清除定时器
this.content = "重新开始倒计时";
totalTime = 60;
this.canClick = true; //这里重新开启
}
}, 1000);
}
},
离开页面时销毁定时器
//beforeDestroy为实例销毁之前调用
beforeDestroy() {
if (this.refreshData) {
// console.log('销毁倒计时')
clearInterval(this.refreshData);
this.refreshData = null;
}
}