方式一:定义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项目中使用$.once(‘hook:beforeDestory‘,() => {})清理定时器问题