4

我正在尝试运行一个函数,该函数发出 GET 请求以更新产品的数量,但仅在currentProductstore 属性存在时。如果没有选定的产品,那么我不想让间隔无缘无故地触发功能。

在伪代码中,我基本上是说:

如果 $this.store.getters['myStore/getCurrentProduct']
然后 setInterval(this.$store.dispatch('updateQuantity'), 2000);

我唯一的想法是为 currentProduct 创建一个计算属性:

computed: {
     currentProd() {
         return $this.store.getters['myStore/getCurrentProduct'];
     }
}

然后观看:

watch: {
     currentProd(newVal,oldVal) {
          if (newVal != null) {
              let foo = setInterval(this.$store.dispatch('updateQuantity'), 2000);
          }
     } 
}

我只是不确定如何防止它重叠并有大量的间隔触发

4

1 回答 1

3

您应该将间隔对象存储在一个地方,以便您可以轻松地重置它,而不是在每次观察者运行时在函数中创建一个新的本地间隔:

data () {
  return {
    productCheckInterval: null
  }
},
watch: {
  currentProd (newVal, oldVal) {
    clearInterval(this.productCheckInterval)
    if (newVal !== null) {
      this.productCheckInterval = setInterval(() => {
        this.$store.dispatch('updateQuantity')
      }, 2000)
    }
  } 
}
于 2020-09-24T15:03:28.057 回答