记录 - 在vue中使用setTimeout,离开当前路由setTimeout未销毁的问题

问题:从第一个页面跳转到第二个页面后,若是停留在第二个页面,定时器还在运行。若是在两个页面之间来回跳转,跳转时间小于定时器的间隔时间时,也会出现重复建立setTimeout的状况。this

缘由:当咱们刷新页面时,会将当前页面以前建立的setTimeout以及其余定时器都清除掉,可是仅仅是路由切换是不会清除的。code

解决:具体代码:`路由

data () {
    return {
      overtimer: null
    }
},
methods: {
    stoptime () {
      clearTimeout(this.overtimer);
    }
},
created () {
    this.overtimer = setTimeout(() => {
        this.$Message.error('读取卡片超时');
     }, 10000)
    this.$once('hook:beforeDestroy', () => {            
      clearInterval(this.overtimer);
      this.overtimer = null;
    })
}

`定时器

相关文章
相关标签/搜索