Svelte 不会在一个分支中更新值

Svelte does not update value in one if branch

我正在尝试在 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'; 永远不会触发反应性变化。

一种方法是 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.

如果有人对一年后的答案感兴趣:

连续多次输入 if-block 不会触发 amountFormatted 的更新,因为值没有改变。它已经是上次调用的 0.00。您可以通过在强制更新之前添加 amountFormatted = 'foo' 一行来测试它。