【发布时间】:2020-03-16 19:55:12
【问题描述】:
我正在尝试让两个输入相互更新
场景:
- 当我在字段 1 中输入 Base-10 数字时,字段 2 必须提供 Base-2 等效数字
- 当我在字段 2 中输入 Base-2 数字时,字段 1 必须给出 Base-10 等效数字
这只是一个假设的场景。我将需要处理这样的问题。我在我的小提琴中提供了一个更基本的例子。
这应该以这种方式发生:
- 当我在 Input-field-1 中进行更改时,Input-field-2 的值必须根据适当的计算进行更改。
- 当我在 Input-field-2 中进行更改时,Input-field-1 的值必须根据适当的计算进行更改。
问题:
- 现在,当我更改 Input-field-1 时,Input-field-2 的值会发生变化,这会产生警告,因为 Input-field-2 中的更改正试图更改 Input-field-1 中的值...我猜这个过程会无限期地继续下去。
- 这个问题没有太大问题,因为 Vue.js 有一个很棒的编译器。但我真的很想知道一个更好的方法来解决这个问题。我尝试尽可能地将变量与函数隔离开来。
我的代码-sn-p:
HTML:
<div id="app">
<div>
I have <input v-model="perc" style="width:3em; text-align:right; background-color:#ffffe0;" v-on:change="amtCal">% of ${{total}}<strong> which is $</strong> <input v-model="amt" style="width:3em; text-align:right; background-color:#ffffe0;" v-on:change="percCal">
</div>
</div>
JS:
new Vue({
el: '#app',
data: {
total:'200',
perc:'10',
amt:''
},
computed:{
amtCal:function(){
this.amt=this.perc/100*this.total
return 0;
},
percCal:function(){
this.perc=this.amt/this.total*100;
return 0;
}
}
})
new Vue({
el: '#app',
data: {
total: '200',
perc: '10',
amt: ''
},
computed: {
amtCal: function() {
this.amt = this.perc / 100 * this.total
return 0;
},
percCal: function() {
this.perc = this.amt / this.total * 100;
return 0;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
I have <input v-model="perc" style="width:3em; text-align:right; background-color:#ffffe0;" v-on:change="amtCal">% of ${{total}}<strong> which is $</strong> <input v-model="amt" style="width:3em; text-align:right; background-color:#ffffe0;" v-on:change="percCal">
</div>
</div>
我意识到:
- 我已使用
v-on:change属性在值更改时执行函数。 - 为了防止输入压倒函数执行,我在其他一些测试中使用了
v-model.lazy。 - 但是,无论我做什么,这个问题似乎都不会消失,因为我的方法存在根本问题。
- 一定有更好的办法。
【问题讨论】:
标签: vue.js