1

I have two variables, for example, priceInUSD and priceInRub and rate USD/Ruble.

data: () => ({
  priceInUSD: 0,
  priceInRub: 0,
  rate: 65.395402,
});

When user changing one variable, the second should be recalcualted. But If I am using watch() for both, it causing of redundant calculation calling and potentially infinity loop. One recalculating second, second calling watch for first, first calling watch for second, and at infinity.

When I am using computed and getters/setters...

computed: {
priceInUSD: {
  get(){
    return this.statePriceInUSD;
  },

  set(newValue){
    this.statePriceInUSD = newValue;
    this.statePriceInRub = newValue * this.rate;
  }
},

priceInRub: {
  get(){
    return this.statePriceInRub;
  },

  set(newValue){
    this.statePriceInRub = newValue;
    this.statePriceInUSD = +newValue / this.rate;
  }
},
}

... it too causing redundant recalculating of other variable.

  1. Changing price in USD
  2. Recalculating price in rubles (ok)
  3. Firing again recalculating price in USD (not ok)

It is possible recalculate two mutually related variables, without redunant recalculating first variable?

mikleSmart
  • 13
  • 4
  • According to my understanding of your question, conversion does not happen properly? please let us know input param and expected output. – SilentCoder Mar 19 '19 at 07:36
  • I am expecting to enter 1 USD and get 65.39 rub as output. But repeated recalculating causing converting from ruble again to USD and outputing it as 0.99999996 USD. User wants to enter in both fileds, but for server is enough only first number as "1". – mikleSmart Mar 19 '19 at 07:59
  • I noticed your question. It is interesting. If I found a solution, I will post here. – SilentCoder Mar 19 '19 at 08:17

1 Answers1

0

This solutions works (you probably screwed up with variables):

new Vue({
  el: "#app",
  data: {
    statePriceInUSD:0,
    statePriceInRub: 0,
    rate: 65.395402,
  },
  computed: {
   priceInUSD: {
     get(){
       return this.statePriceInUSD;
     },

     set(newValue){
        console.log('USD new value: ' + newValue);
        this.statePriceInUSD = newValue;
        this.statePriceInRub = newValue * this.rate;
     }
},

priceInRub: {
  get(){
    return this.statePriceInRub;
  },

  set(newValue){
      console.log('RUB new value: ' + newValue);
      this.statePriceInRub = newValue;
      this.statePriceInUSD = +newValue / this.rate;
   }
},
}
})

Working example is here https://jsfiddle.net/a4ped21h/

Skipper
  • 366
  • 3
  • 6