在一个页面中定时器调用一个接口,切换别的路由时候定时器需要清空。是在mounted 和beforeDestroy做的不起用
1.data中定义 timers:null
mounted () {
this.timers = setInterval(() => {
this.loadData()
}, 30000)
},
beforeDestroy () {
clearInterval(this.timers)
this.timers = null
},
3、解决方法:
把定时器的任务定义在activated事件,这样子,当清除定时后,下次再次进入当前路由的话,可以再次唤起定时器
activated() {
this.timers = setInterval(() => {
this.loadData()
}, 30000)
},
4、使用路由内的组件守卫beforeRouteLeave
beforeRouteLeave(to, from, next){
next()
if (this.timers) {
clearInterval(this.timers)
this.timers = null
}
}