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

阅读 72

2022-04-20

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

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

精彩评论(0)

0 0 举报