为了账号安全,请及时绑定邮箱和手机立即绑定

Vuex:仅当存储属性存在时每 2 秒调度一个函数?

Vuex:仅当存储属性存在时每 2 秒调度一个函数?

慕娘9325324 2023-03-24 14:09:48
我正在尝试运行一个函数,该函数发出 GET 请求以更新产品数量,但仅当商店currentProduct属性存在时。如果没有选定的产品,那么我不想让间隔无缘无故地触发一个功能。在伪代码中,我基本上是说:如果 $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);          }     } }我只是不确定如何防止它重叠并且有大量的间隔触发
查看完整描述

1 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

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


data () {

  return {

    productCheckInterval: null

  }

},

watch: {

  currentProd (newVal, oldVal) {

    clearInterval(this.productCheckInterval)

    if (newVal !== null) {

      this.productCheckInterval = setInterval(() => {

        this.$store.dispatch('updateQuantity')

      }, 2000)

    }

  } 

}


查看完整回答
反对 回复 2023-03-24
  • 1 回答
  • 0 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号