mounted() {
// 创建一个定时器
this.timer = setInterval(() => {
// ......
}, 500);
},
// 销毁这个定时器。
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
上面是我们经常使用的创建定时器,在页面被销毁之前清空定时器;但是因为不再一个地方,可能会有遗忘,而忘记去清理定时器;
使用hook可以帮我们轻松解决定时器清除问题
mounted() {
let timer = setInterval(() => {
// ......
}, 500);
this.$once('hook:beforeDestroy', function() {
if (timer) {
clearInterval(timer);
timer = null;
}
});
}
Vue使用hook销毁定时器
最新推荐文章于 2024-02-20 17:59:53 发布