我有两个变量,例如,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;
}
},
}
...它也导致冗余重新计算其他变量。
有可能重新计算两个相互关联的变量,而不重复计算第一个变量?
这个解决方案有效(你可能搞砸了变量):
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;
}
},
}
})