vue中如何优雅的清除定时器

$once 监听一个自定义事件,但是只触发一次。一旦触发之后,监听器就会被移除。

程序化清理监听器,在组件内的beforeDestory钩子中清除

  mounted () {
    
    
    const that = this
    // 设置定时器
    const timer= setInterval(() => {
    
    
      setTimeout(() => {
    
    
        console.log('test clearInterval')
      }, 0)
    }, 2000)
    // 通过$once来监听生命周期beforeDestroy钩子,在组件销毁前清除定时器。
    this.$once('hook:beforeDestroy', () => {
    
    
      clearInterval(timer)
    })

猜你喜欢

转载自blog.csdn.net/qq_42931285/article/details/124288085
今日推荐