programing

Vuex: 스토어 속성이 존재하는 경우에만 2초마다 함수를 디스패치하시겠습니까?

randomtip 2022. 9. 23. 21:40
반응형

Vuex: 스토어 속성이 존재하는 경우에만 2초마다 함수를 디스패치하시겠습니까?

제품의 수량을 업데이트하기 위해 GET 요청을 하는 기능을 실행하려고 하는데, 이 기능은 제품 수량을 업데이트 할 때에만 실행됩니다.currentProduct스토어 속성이 존재합니다.선택된 제품이 없다면, 나는 아무 이유 없이 함수를 실행하는 간격을 두고 싶지 않다.

의사 코드로, 기본적으로 다음과 같이 말할 수 있습니다.

$이것이라면.store.getters['myStore/getCurrentProduct']
다음으로 setInterval(이것)을 지정합니다.$store.dispatch("update Quantity", 2000);

제 유일한 생각은 current Product에 대해 계산된 속성을 만드는 것이었습니다.

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)
    }
  } 
}

언급URL : https://stackoverflow.com/questions/64048507/vuex-dispatch-a-function-every-2-seconds-only-when-a-store-property-exists

반응형