我正在尝试在 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';
永远不会触发反应性更改。
答案 0 :(得分:1)
一种方法是使用 bind
作品
<input
type="tel"
bind:value={amountFormatted} // Not sure why without bind is not working, need to explore
bind:this={currencyInput}
on:input={handleChange}
/>
或者第二个:
if (cleanedInput.length === 0 ) {
console.log('setting amountFormatted to 0.00 --- BUT IT does not work ');
currencyInput.value = '0.00'; // this works
} else {
amountFormatted = (parseInt(cleanedInput, 10) / 100).toString();
}
<input
type="tel"
value={amountFormatted}
bind:this={currencyInput}
on:input={handleChange}
/>
根据Svelte REPL,我了解到对于numeric inputs
,
value={somevaribale} is one way binding
bind:value={somevaribale} is two way binding.