方式一:定义data中定义timer
export default {
data() {
return {
timer: null,
};
},
methods: {
startTimer() {
this.timer = setInterval(() => {
}, 1000);
},
stopTimer() {
clearInterval(this.timer);
this.timer = null;
},
},
mounted() {
this.startTimer();
},
beforeDestroy() {
this.stopTimer();
},
};
方式二:监听事件hook:beforeDestroy
export default {
methods: {
startTimer() {
let timer = setInterval(() => {
console.log(11111);
}, 1000);
this.$once('hook:beforeDestroy', () => {
clearInterval(timer);
timer = null;
});
},
},
mounted() {
this.startTimer();
},
};
Vue:使用定时器timer及其清理hook:beforeDestory