itsource

vue.flash 워치가 업데이트되지 않았습니다.

mycopycode 2022. 12. 4. 22:36
반응형

vue.flash 워치가 업데이트되지 않았습니다.

나는 vue에 처음 와봐요.이제 다른 계산 변수의 변경을 기반으로 몇 가지 변수를 업데이트하려고 합니다.

이 계산된 변수는 Vuex 저장소에서 값을 가져와 정상적으로 작동합니다.가치관이 변하는 걸 알겠네요파생 변수를 계산하기 위해 계산된 변수를 감시하고 이러한 파생 값을 업데이트하는 워치를 만들었습니다.이 워치는 시작 시 두 번 호출되며 이후 더 이상 호출되지 않습니다. 단, 계산된 값은 계속 업데이트됩니다.내가 뭘 잘못하고 있지?

동작하고 있습니다.

...
computed: {
    lastAndMarkPrice() {
      return store.getters.getLastAndMarkPriceByExchange(
        "deribit",
        store.getters.getAsset
      );
    },
...

이 부품이 작동하지 않습니다.

...
data: () => ({
    lastPriceUp: false,
    lastPriceDn: false,
    markPriceUp: false,
    markPriceDn: false,
  }),
...
watch: {
    lastAndMarkPrice (newValue, oldValue) {
      console.log(newValue, oldValue);
      this.lastPriceUp = newValue.lastPrice > oldValue.lastPrice;
      this.lastPriceDn = newValue.lastPrice < oldValue.lastPrice;
      this.markPriceUp = newValue.markPrice > oldValue.markPrice;
      this.markPriceDn = newValue.markPrice < oldValue.markPrice;
    },
  },
...

디폴트로는 awatch얕다.새 개체가 할당된 경우lastAndMarkPrice핸들러가 호출되지만 해당 오브젝트 내의 속성 돌연변이는 체크되지 않습니다.

딥워처를 작성하려면 다음과 같은 작업을 수행합니다.

watch: {
  lastAndMarkPrice: {
    deep: true,

    handler (newValue, oldValue) {
      // ...
    }
  }
}

https://vuejs.org/v2/api/ #워치

일반적으로는 이 솔루션이 올바른 솔루션이지만 이전 가치에 액세스해야 하기 때문에 사용 사례는 조금 더 복잡합니다.깊은 관찰자를 사용하는 것은 같은 대상을 통과하기 때문에 도움이 되지 않습니다.

이 문제를 해결하려면 이전 값의 복사본을 어딘가에 복사하여 새 값과 비교할 수 있도록 해야 합니다.이를 위한 한 가지 방법은 계산된 속성을 복사하는 것입니다.

computed: {
  lastAndMarkPrice() {
    const prices = store.getters.getLastAndMarkPriceByExchange(
      "deribit",
      store.getters.getAsset
    );

    // I'm assuming that prices is initially null or undefined.
    // You may not need this bit if it isn't.
    if (!prices) {
      return null;
    }

    return {
      lastPrice: prices.lastPrice,
      markPrice: prices.markPrice
    }
  }
}

위의 코드를 사용하면 매번 값이lastPrice또는markPrice그러면 계산된 속성이 다시 실행되고 새 개체가 생성됩니다.이 때문에,watch핸들러에서는, 중요한 것은, 2개의 다른 오브젝트가 낡은 값과 새로운 값으로 건네진다는 것입니다.사용할 필요가 없습니다.deep이 경우 오브젝트 내의 속성뿐만 아니라 오브젝트 자체가 변화하고 있습니다.

또, 조금 짧게 할 수도 있습니다.

return { ...prices }

...두 속성을 명시적으로 복사하는 것이 아니라.

언급URL : https://stackoverflow.com/questions/62981171/vue-js-watch-not-updated

반응형