在 Vue 上观察两个相互关联的变量
Watch two mutually related variables on Vue
我有两个变量,例如,priceInUSD 和 priceInRub 和 rate USD/Ruble.
data: () => ({
priceInUSD: 0,
priceInRub: 0,
rate: 65.395402,
});
当用户更改一个变量时,应该重新计算第二个。但是如果我对两者都使用 watch() ,它会导致冗余计算调用和潜在的无限循环。一个重新计算第二个,第二个调用 watch for first,first calling watch for second, and at infinity.
当我使用计算和 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;
}
},
}
...它太导致其他变量的冗余重新计算。
- 更改美元价格
- 重新计算卢布价格(确定)
- 再次触发以美元重新计算价格(不正常)
是否可以重新计算两个相互关联的变量,而无需重新计算第一个变量?
这个解决方案有效(你可能搞砸了变量):
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;
}
},
}
})
我有两个变量,例如,priceInUSD 和 priceInRub 和 rate USD/Ruble.
data: () => ({
priceInUSD: 0,
priceInRub: 0,
rate: 65.395402,
});
当用户更改一个变量时,应该重新计算第二个。但是如果我对两者都使用 watch() ,它会导致冗余计算调用和潜在的无限循环。一个重新计算第二个,第二个调用 watch for first,first calling watch for second, and at infinity.
当我使用计算和 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;
}
},
}
...它太导致其他变量的冗余重新计算。
- 更改美元价格
- 重新计算卢布价格(确定)
- 再次触发以美元重新计算价格(不正常)
是否可以重新计算两个相互关联的变量,而无需重新计算第一个变量?
这个解决方案有效(你可能搞砸了变量):
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;
}
},
}
})