data() {
return {
timer: null,//data中定义timer变量
index:0,
}
}
methods: {
loadtime() {
this.timer = setInterval(() => {//用箭头函数来确定this不然指向Windows
this.index++;
console.log(this.index);
}, 1000);
},
clearTimer() {
//清除定时器
clearInterval(this.timer);
this.timer = null;
},
},
mounted() {
this.loadtime();
},
beforeUnmount() {//离开清除定时器
clearInterval(this.timer);
this.timer = null;
},