我有使用 vuejs watch 属性来响应输入的代码。代码链接是 https://playcode.io/1264493
这里是您可以看到,当尝试输入名为“百分比”的值时,它会重新计算该值。这是预期的,因为它正在被监视,并且其他输入也正在被监视。除了使用超时之外,有什么方法可以做到这一点而不会引起这种紧张的行为。也精确到 2 位小数。实际上它不应该跳到小数点末尾,然后输入值应该很容易。除了少数输入外,所有输入都发生了。例如,在“百分比”输入上输入值 7 会显示出奇怪的行为。计算也发生同样的情况。
代码也附在这里
<script setup>
import {reactive, watch} from 'vue'
const data = reactive({
first : 50000,
second : 20000,
percentage : ''
})
watch(() => data.percentage,
(newValue, oldValue) => {
data.second = (data.first*newValue)/100
}
)
watch(() => data.second,
(newValue, oldValue) => {
data.percentage = (newValue/data.first)*100
}
)
</script>
<template>
<div>
<div>
<label>First</label>
<input type="text" v-model="data.first">
</div>
<div style="padding: 15px 0px">
<label>Second</label>
<input type="text" v-model="data.second">
</div>
<div>
<label>Percentage</label>
<input type="text" v-model="data.percentage">
</div>
</div>
</template>
我认为你不应该创建 2 个会修改彼此值的手表,因为它们可能会相互触发多次。
我更喜欢使用在您键入时执行的函数。
<script setup>
import {reactive, watch} from 'vue'
const data = reactive({
first : 50000,
second : 20000,
percentage : ''
})
const handlePercentage = () => {
data.second = (data.first*Number(data.percentage))/100
}
const handleSecond = () => {
data.percentage = (Number(data.second)/data.first)*100
}
</script>
<template>
<div>
<div>
<label>First</label>
<input type="text" v-model="data.first">
</div>
<div style="padding: 15px 0px">
<label>Second</label>
<input type="text" v-model="data.second" @input="handleSecond">
</div>
<div>
<label>Percentage</label>
<input type="text" v-model="data.percentage" @input="handlePercentage">
</div>
</div>
</template>