首先在项目的入口App.vue中使用watch对路由route进行判断,当路由不是指定的"Dashboard"路由时执行事件触发,关闭定时任务:
watch: {
$route: {
handler (newValue) {
if (newValue.name != "Dashboard") {
events.$emit('clearInterval')
}
},
immediate: true
}
}
其中执行定时任务的setInterval和关闭定时任务的clearInterval方法写在Dashboard这个页面中:
mounted () {
events.$on('clearInterval', val => {
clearInterval(this.interval)
})
clearInterval(this.interval)
this.init()
this.interval = setInterval(() => {
this.init()
}, 60000)
},
methods: {
由上面可以看出,在这个页面下,每60s执行一次定时任务,当路由不在Dashboard时,关闭定时任务。