我正在研究单位换算应用程序,以将医疗单位从美国单位转换为国际(SI)单位。我正在尝试对每个US和SI转换使用单独的输入,以便当一个输入值更改时,另一个输入根据新值更改。每次转换都会使用一个因子进行计算。我有一个简单的示例设置,该示例将在加载时填充输入值,但无法使输入更改功能起作用。
这是我的代码:
<script>
let units = [{
"name": "Acetaminophen",
"specimen": "Serum, Plasma",
"conventionalRange": "10-30",
"conventionalUnit": "µg/mL",
"factor": "6.614",
"siRange": "66-200",
"siUnit": "µmol/L",
"siValue": "66",
"usValue": "10"
}, {
"name": "Acetoacetate",
"specimen": "Serum, Plasma",
"conventionalRange": "<1",
"conventionalUnit": "mg/dL",
"factor": "97.95",
"siRange": "<100",
"siUnit": "µmol/L",
"siValue": "100",
"usValue": "1"
}, {
"name": "Acetone",
"specimen": "Serum, Plasma",
"conventionalRange": "<1.0",
"conventionalUnit": "mg/dL",
"factor": "0.172",
"siRange": "<0.17",
"siUnit": "mmol/L",
"siValue": "0.17",
"usValue": "1.0"
}, {
"name": "Acid phosphatase",
"specimen": "Serum",
"conventionalRange": "<5.5",
"conventionalUnit": "U/L",
"factor": "16.667",
"siRange": "<90",
"siUnit": "nkat/L",
"siValue": "90",
"usValue": "5.5"
}, {
"name": "Activated partial thromboplastin time (APTT)",
"specimen": "Whole blood",
"conventionalRange": "25-40",
"conventionalUnit": "s",
"factor": "1",
"siRange": "25-40",
"siUnit": "s",
"siValue": "25",
"usValue": "25"
}
]
let factor = '';
let siValue = '';
let usValue = '';
function setBothFromSI(value) {
siValue = +value;
usValue = +(siValue / factor).toFixed(2);
}
function setBothFromUS(value) {
usValue = +value;
siValue = +(usValue * factor).toFixed(2);;
}
</script>
<style>input{max-width:150px}
.bold{font-weight:600;}
</style>
{#each units as { usValue,siValue,siUnit,siRange,conventionalUnit,conventionalRange,specimen,name, factor}, i}
<p class=bold >{name}</p>
<label>
US Value
<input value={usValue} on:input="{e => setBothFromUS(e.target.value)}" min="" type=number placeholder=" US">
</label>
<label>
SI Value
<input value={siValue} on:input="{e => setBothFromSI(e.target.value)}" min="" type=number placeholder="SI">
</label>
{/each}
任何帮助将不胜感激
答案 0 :(得分:0)
看起来唯一的问题是在setBothFromSI
和setBothFromUS
中,您试图更新变量siValue
和usValue
。但是没有任何东西可以渲染这些变量,由于unit
块,您的输入实际上正在渲染每个{#each units as { usValue, siValue } }
中包含的值
因此在那些setBoth
函数中,您可能想要更新units
内部的值,如下所示:
function setBothFromSI(value, i) {
const { factor } = units[i];
units[i].siValue = +value;
units[i].usValue = +(value / factor).toFixed(2);
}
function setBothFromUS(value, i) {
const { factor } = units[i];
units[i].usValue = +value;
units[i].siValue = +(value * factor).toFixed(2);;
}
然后确保将索引传递给此类函数
<input value={usValue} on:input="{e => setBothFromUS(e.target.value, i)}" min="" type=number placeholder=" US">
这里是updated REPL