为什么Vue的beforeDestroyed钩子无法正常清除setInterval定时器?
问题排查与修复方案
核心错误点
- 未存储定时器ID:
setInterval执行后会返回一个唯一的数字ID,这是clearInterval唯一可识别的清除依据,你当前代码直接将自定义方法this.clock作为入参传入清除方法,完全无法匹配到对应的定时器,因此清除失败。 - (可选校验)生命周期钩子拼写问题:Vue 2.x的销毁前钩子名为
beforeDestroy,Vue 3.x对应的销毁前钩子名为beforeUnmount,你使用的beforeDestroyed并非标准钩子名,如果你的运行环境没有特殊兼容,即使能打印日志也建议修正为对应框架版本的标准钩子名。
修复后代码
// 第一步:data中新增变量存储定时器ID data() { return { timer: null } }, methods: { clock() { const date = new Date() const hours = ((date.getHours() + 11) % 12 + 1); const minutes = date.getMinutes(); const seconds = date.getSeconds(); const hour = hours * 30; const minute = minutes * 6; const second = seconds * 6; // 你原本的时钟渲染逻辑写在这里即可 }}, mounted: function() { // 第二步:存储定时器返回的ID this.timer = setInterval(this.clock, 1000); }, // 第三步:修正钩子名,用存储的ID清除定时器 beforeDestroy: function() { console.log("workBefore") if (this.timer) { clearInterval(this.timer); this.timer = null; } }
内容的提问来源于stack exchange,提问作者egx
相关产品推荐
相关产品推荐

