javascript - Vuex:仅当存在商店属性时每 2 秒调度一次函数?

标签 javascript vue.js vuejs2 vuex

我正在尝试运行一个函数,该函数发出 GET 请求以更新产品的数量,但仅当 currentProduct store 属性存在。如果没有选定的产品,那么我不想让间隔无缘无故地触发功能。
在伪代码中,我基本上是说:

if $this.store.getters['myStore/getCurrentProduct']
then 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);
          }
     } 
}
我只是不确定如何防止它重叠并有大量的间隔触发

最佳答案

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

data () {
  return {
    productCheckInterval: null
  }
},
watch: {
  currentProd (newVal, oldVal) {
    clearInterval(this.productCheckInterval)
    if (newVal !== null) {
      this.productCheckInterval = setInterval(() => {
        this.$store.dispatch('updateQuantity')
      }, 2000)
    }
  } 
}

关于javascript - Vuex:仅当存在商店属性时每 2 秒调度一次函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64048507/

相关文章:

javascript - Typescript 数组是否为空索引分配内存?

vue.js - 当 vuex store 中的特定状态发生变化时发出事件

vue.js - *.vue 文件、Visual Studio 2017 和 TypeScript

javascript - 在 Vue JS 上根据父属性生成 id

javascript - 通过编程导航 Vue.js 传递 Prop

javascript - 我怎样才能通过javascript知道html的显示部分是什么

javascript - React、TransitionGroup、Velocity.js - 使路由过渡动画垂直对齐

javascript - 增加 Horizo​​n 系列的值(value)

javascript - 组件渲染后如何聚焦到特定的输入文本?

javascript - 如何在 Angular Directive(指令)中正确显示json