···
<script>
export default {
data() {
return {
// 刷新间隔
stepNum: 100,
// 设置定时器开关
interval: null
}
},
// 之前在大的主组件中使用了 keep-alive 缓存
activated() {
if (this.interval === null) {
...
// 第一次使用定时器时必然为null,所以此时启动定时器
this.refreshData()
}
},
// 路由跳转之前关闭定时器
beforeRouteLeave(to, from, next) {
...
// 如果有定时器则关闭定时器
if (this.interval) {
clearInterval(this.interval)
this.interval = null
}
next()
},
methods: {
...
refreshData() {
if (this.interval === null) {
this.interval = setInterval(() => {
...
// 刷新函数
...
}, this.stepNum * 1000)
} else {
clearInterval(this.interval)
this.interval = setInterval(() => {
...
// 刷新函数
...
}, this.stepNum * 1000)
}
},
// 定时器间隔改变函数
stepNumChange() {
if (!this.interval) {
clearInterval(this.interval)
}
this.refreshData()
}
}
}
</script>