【发布时间】:2021-04-21 12:56:53
【问题描述】:
我正在尝试在 Svelte 中实现一些货币输入。
几乎所有东西都可以例外,但如果我删除带有Backspace 的字段中的输入,我可以看到日志消息,但该值未设置为'0.00'。
我为此准备了一个 REPL:https://svelte.dev/repl/2b83934eff9747a1a1c7a15c976be316?version=3.31.2
<script>
let amountFormatted = '0.00';
let currencyInput;
$: console.log('amountFormatted: ' + amountFormatted);
const handleChange = () => {
console.log('currentInput: ' + currencyInput.value);
let cleanedInput = currencyInput.value
.replace(/\D*/gm, '') // remove non digits
.replace(/^0+/gm, ''); // remove leading zeros
console.log('cleanedInput.length: ' + cleanedInput.length);
if (cleanedInput.length === 0 ) {
console.log('setting amountFormatted to 0.00 --- BUT IT does not work ');
amountFormatted = '0.00'; // ERROR this never works
} else {
amountFormatted = (parseInt(cleanedInput, 10) / 100).toString();
}
};
</script>
<input
type="tel"
value={amountFormatted}
bind:this={currencyInput}
on:input={handleChange}
/>
我几乎要花一整天的时间来完成这项工作。我尝试了诸如tick() 之类的东西以及许多其他东西,但似乎amountFormatted = '0.00'; 从未触发过响应式更改。
【问题讨论】:
-
currencyInput.value = '0.00';做这个工作 -
是的,现在可以了。非常感谢。但我仍然很好奇为什么其他方法不起作用!但是我要非常感谢你!!!