在Vue上观察两个相互关联的变量

问题描述 投票:1回答:1

我有两个变量,例如,priceInUSD和priceInRub以及美元/卢布的汇率。

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

当用户更改一个变量时,应重新计算第二个变量。但是,如果我对两者都使用watch(),则会导致冗余计算调用和潜在的无限循环。一个重新计算的第二个,第二个呼叫表,第一个,第一个呼叫表,第二个和无限。

当我使用计算机和getter / setter时......

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;
  }
},
}

...它也导致冗余重新计算其他变量。

  1. 以美元换价
  2. 用卢布重新计算价格(好)
  3. 重新计算再次计算美元价格(不行)

有可能重新计算两个相互关联的变量,而不重复计算第一个变量?

loops vue.js vuejs2 watch
1个回答
0
投票

这个解决方案有效(你可能搞砸了变量):

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

工作示例在这里https://jsfiddle.net/a4ped21h/

© www.soinside.com 2019 - 2024. All rights reserved.