Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

vue 清除异步产生的定时器

遇到的如下场景:

使用了async created钩子, await某个请求完成后,设置this.timer为定时器

问题如下:

  • 如果用户在请求结束后才离开页面,我们可以在beforeDestory中clear定时器,没什么问题。
  • 如果用户在请求结束前离开页面(此时即使离开了页面created钩子仍然会执行),请问如何不生成、或者生成后clear这个定时器?

解决方法:
暂时想到的只有axios的 canceltoken去停止请求。请问有更好的设计方式或者解决方案吗?

----更新
暂时又想到了一个 在定时器里判断 this._isDestroyed 如果是true就擦掉这个定时器


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

我觉得你那两个想法是可以的,不过如果很多组件使用的话会比较麻烦点,我建议你整一个mixin封装一下。
类似这样:

const VueTimer = {
    beforeCreate() {
      this.$timerMap = {}
      this.$setTimeout = (handler, timeout) => {
        if (!this._isDestroyed) {
          this.$timerMap[setTimeout(handler, timeout)] = timeout
        }
      }
    },
    beforeDestroy() {
      Object.keys(this.$timerMap).forEach((timer) => {
        clearTimeout(timer)
      })
    }
}

然后全局注册下

Vue.mixin(VueTimer)

组件里使用

created() {
  this.$setTimeout(() => {
    console.log('timer')
  }, 1000)
}

这样就不需要每次判断了,VueTimer将会在组件销毁时自动清空定时器


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...