gpt4 book ai didi

javascript - 获取设置交叉引用

转载 作者:搜寻专家 更新时间:2023-10-30 22:59:57 24 4
gpt4 key购买 nike

我正在尝试制作一个具有 3 个相互依赖的输入的工具; “赚取 %”、“赚取 $”和“自己的价格”。

默认情况下,“收入百分比”为“10”,因此初始计算有效......如果我只更改这个值,其他两个值将适应,因为没有循环引用/交叉引用: https://jsfiddle.net/2m971kur/2/

const app = new Vue({
el: '#app',
data: {
exVAT: 1500,
retailPrice: 2900,
earnPercentage: 10
},
computed: {
incVAT() {
return this.exVAT * 1.25;
},
ownPrice() {
return this.exVAT + (this.exVAT * (this.earnPercentage / 100));
},
earnAmount() {
return this.ownPrice - this.exVAT;
}
}
})

但是...
如果我尝试进行循环引用/交叉引用,我的代码就会中断: https://jsfiddle.net/xrwykvg5/

const app = new Vue({
el: '#app',
data: {
exVAT: 1500,
retailPrice: 2900,
earnPercentage: 10,
ownPrice: 0,
earnAmount: 0
},
watch: {
earnPercentage() {
this.earnAmount = this.exVAT * (this.earnPercentage / 100);
this.ownPrice = this.exVAT + this.earnPercentage;
},
ownPrice() {
this.earnAmount = this.ownPrice - this.exVAT;
this.earnPercentage = 100 / (this.ownPrice / this.exVAT);
},
earnAmount() {
this.ownPrice = this.exVAT + this.earnAmount;
this.earnPercentage = (this.ownPrice / this.exVAT) * 100;
}
}
})

我怎样才能克服这个问题?

例子是用 Vue.js 制作的,只是为了展示我的问题的一个快速简单的例子。我的真实代码在 Angular 2 中。

最佳答案

我完全相信 Roy J 有能力找到一个具有优雅和简洁的计算属性的工作版本。

在我这边,我很脏。更准确地说,我没有勇气去真正理解你的逻辑来完全重构它。所以这是我的解决方案,使用简单的方法:

const app3 = new Vue({
el: '#app',
data: {
incVAT: 0,
exVAT: 1500,
retailPrice: 2900,
earnPercentage: 10,
ownPrice: 0,
earnAmount: 0
},
methods: {
changeEarnPercentage(earnPercentage) {
this.earnPercentage = Number(earnPercentage);
this.earnAmount = this.exVAT * (this.earnPercentage / 100);
this.ownPrice = this.exVAT + this.earnPercentage;
},
changeOwnPrice(ownPrice) {
this.ownPrice = Number(ownPrice);
this.earnAmount = this.ownPrice - this.exVAT;
this.earnPercentage = 100 / (this.ownPrice / this.exVAT);
},
changeEarnAmount(earnAmount) {
this.earnAmount = Number(earnAmount);
this.ownPrice = this.exVAT + this.earnAmount;
this.earnPercentage = (this.ownPrice / this.exVAT) * 100;
}
}
})
#app div {
float: left;
margin: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
<div>
Inc. VAT: <br>{{ incVAT }}
</div>
<div>
Ex. VAT: <br>{{ exVAT }}
</div>
<div>
% earned: <br>
<input type="text" :value="earnPercentage" @input="changeEarnPercentage($event.target.value)" />
</div>
<div>
$ earned: <br><input type="text" :value="earnAmount" @input="changeEarnAmount($event.target.value)" />
</div>
<div>
Own price: <br><input type="text" :value="ownPrice" @input="changeOwnPrice($event.target.value)" />
</div>
<div>
Retail: <br>{{ retailPrice }}
</div>
</div>

看起来终于没那么糟糕了。

请注意,我添加了一些 Number() 转换,因为您可能不想将它们连接为字符串。另外,我建议您使用 <input type="number">相反。

关于javascript - 获取设置交叉引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44654516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com