开发中用到定时器时我们一般这样
// bad mounted() { // 创建一个定时器 this.timer = setInterval(() => { // ...... }, 500); }, // 销毁这个定时器。 beforeDestroy() { if (this.timer) { clearInterval(this.timer); this.timer = null; } }
而借助 hook,可以更方便维护
// good mounted() { let timer = setInterval(() => { // ...... }, 500); this.$once("hook:beforeDestroy", function() { if (timer) { clearInterval(timer); timer = null; } }); }