vue定时器,hook监听生命周期钩子清除定时器

1,423 阅读1分钟

常用定时器写法

vue 定时器注册后,在生命周期前beforeDestroy必须清除定时器

  // 组件被挂载后
  mounted(){
    // 注册定时器
    this.timer=setInterval(()=>{},1000) 
  },
  // 组件被卸载之前
  beforeDestroy(){
    // 清理定时器
    clearInterval( this.timer)
  },

这种写法有2个潜在问题:

1: 在组件保存了this.timer。

2: 注册和清理定时器分别在mounted和beforeDestroy生命钩子,如果两个生命钩子中间有很多行代码不方便程序化阅读

利用$once和hook 监听生命钩子

 // 组件被挂载后
  mounted(){
    // 注册定时器
    const timer=setInterval(()=>{},1000) 
    // 清理定时器
    this.$once('hook:beforeDestroy',()=>{clearInterval(timer)})
  },